简体   繁体   中英

Simple Ajax call with result handler does not work

I got this JS:

<script>
jQuery(document).ready(function(){ // we wait until DOM is ready
    jQuery('#veranstort').change(function(){ // fire when input is filled

        origin = "55767 Schwollen";
        destination = "13509 Berlin";

        jQuery.ajax({ // we build the AJAX request
                method:"POST", 
                url:"index.php?option=com_rsform&formId=6&action=ajax", 
                data: {origin, destination},
                success: function(results) {
                    console.log("results: " + results);

                }
        });
    });
})
</script>

which fires this php script:

$action = JRequest::getWord('action'); // we will need a parameter to run the script
if ($action == "ajax") { // if condition is met, run the script

    $origin = $_POST['origin']; // get the origin
    $destination = $_POST['destination']; // get the destination
    var_dump("destination: ".$destination); // this gives me NULL!!

    $distance = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin."&destinations=".$destination."&key=GMAPSKEY"); // build the URL according to the API

    $distance = json_decode($distance); // decode the response from JSON

    print_r($distance->rows[0]->elements[0]->distance->text);die(); // print the result so we can catch it in the AJAX call

}

This has worked for a while, but now it does not. I cant access the destination or origin value in php.. What am I doing wrong?

The Error came from the missing / in the URL. It got redirected, and the POST data got lost with this process.

correct URL:

url:"/index.php?option=com_rsform&formId=6&action=ajax"

Script file it's fine . Please change the ajax file condition.

$action = $_GET['action'];

if ($action == "ajax") { // if condition is met, run the script


     //// Here process your code
}

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