简体   繁体   中英

Get and display results of PHP using jQuery/AJAX

I have a Leaflet map, and a text input. I want to take the address from the textbox, run it through a PHP script, and get the result all through jQuery.

Here is my form:

        <form id="mapcheck" method="POST" action="geo.php">
            <input id="largetxt" type="text" name="checkAddress">
            <input id="button" type="submit" name="submit" value="Check">
        </form>

Here is part of the PHP:

 <?php
            if (isset($_POST["checkAddress"])) { //Checks if action value exists
            $checkAddress = $_POST["checkAddress"];
            $plus = str_replace(" ", "+", $checkAddress);
            $json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $plus . '&key=GMAPSKEY');
            $obj = json_decode($json);
            $mapLat = $obj->results[0]->geometry->location->lat;
            $mapLng = $obj->results[0]->geometry->location->lng;
            $coords = ('' . $mapLat . ', ' . $mapLng . '');
            return $coords;
        }
    ?>


And the jQuery:

$(document).ready(function() {
    $("#button").click(function(){
        $.ajax({
            url: "geo.php",
            method: "POST",
            data: {
             checkAddress: $("#largetxt").val()
            },
            success: function(response){
             console.log(response);
            }
        });
    });
});

I need to listen on submit of the form via jQuery (NOT PHP), run it through a geocode script, then take that result and put it through regular JavaScript (Leaflet map.) I have played around with the AJAX feature of jQuery to no avail. There is a very simple solution to this, but I have not figured it out.

UPDATE: Problem resolved, thanks Vic.

You would need AJAX. Remove the form element but keep the inputs.

$("#button").click(function(){
    $.ajax({
         url: "geo.php",
         method: "POST",
         data: {
             checkAddress: $("#largeText").val()
         },
         success: function(response){
             console.log(response);
             //your script
         }
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM