简体   繁体   中英

AJAX to post javascript variable to php

My question is: using AJAX, how do I pass a variable in Javascript to my PHP code?

I know PHP is server-side and Javascript is client side and I've read at least a dozen questions asking almost or pretty much the same thing but with each one I seem to be missing something because none of them work. In essence, I am using geolocation to get the user's latitude and longitude on page load and for testing purposes it displays it on the page in respective divs. This part works fine. My issue comes when I try to submit the data to my PHP variables it doesn't connect or something goes wrong, or maybe my code is completely incorrect on this part.

Here is my page for testing in its entirety "test.php":

<!DOCTYPE html>
<html>
  <head>
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

   <script>
     x = navigator.geolocation;

     x.getCurrentPosition(success, failure);

     function success(position) {
        var mylat = position.coords.latitude;
        var mylng = position.coords.longitude;
        $('#latit').html(mylat);
        $('#longit').html(mylng);
     }
     function failure() {
        $('#latit').html("<p>It didn't work</p>")
     }

     //sends javascript 'mylat' and 'mylng' from above to php script//
    $.post("test.php", { lat: mylat , lng : mylng});

   </script> 


  </head>
  <body>
    <!--only to validate that geolocation function works-->
    <div id="latit"></div>
    <div id="longit"></div>

    <div id="splash">
        <h2>Click the button</h2>
        <form action="test.php" method="post">


        <input type="submit" name="submit" value="Do the thing!" />
        </form>
    </div>

    <?php
        //used to validate passing of coordinates
    if (isset($_POST['lat'])) {
        echo $lat = $_POST['lat'];
    }
    if (isset($_POST['lng'])) {
        echo $lng = $_POST['lng'];
    }
    ?>
  </body>
</html>

I am attempting to pass the JS 'mylat' and 'mylng' into PHP's $lat and $lng respectively. Any help would be sincerely appreciated and I apologize for the duplicate question, I'm not sure of a better way to frame what I'm asking for.

Additionally, if there's a way to do this without having to click anything that would be a bonus but I've found nothing for that. I'm very new to web development/programming in general and have almost no experience with Javascript/jQuery/AJAX.

Firstly, this line:

$.post("test.php", { lat: mylat , lng : mylng});

should be in the success function. Where it is now it gets executed as soon as the browser parses the <script> tag, however you need to make the POST request when you get the location.

And secondly the ajax request you've made won't have effect on the already loaded page, as the results of it will vanish, unless processed.

What you can do is to use $.load() on the body element, this will replace the contents of the current body with the received one:

$(document.body).load("test.php", { lat: mylat , lng : mylng});

Although a better approach would be to have a script that processes the location send via ajax and you render that received content into a custom element from your html page.

Your function named "success" is where you are defining the variables myLat and myLng. When you are making the POST request to the server you are trying to pass the variables' values, but nothing is coming through, right? The reason for that is because your post request doesn't have access to the scope of that function.

Try moving the $.post request into the success function, so that it reads like this:

function success(position) {
    var mylat = position.coords.latitude;
    var mylng = position.coords.longitude;
    $('#latit').html(mylat);
    $('#longit').html(mylng);
    $.post("test.php", { lat: mylat , lng : mylng});
 }

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