Unable to make a ajax async post request to the same page

I'm trying to make an async call to the same page but for some reason, the async call is not being made and hence getting "userinfo" undefined error! could someone please tell me what I'm doing wrong in this thank you!

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
    $( document ).ready(function() {
    //getting location of the user and assigning it to the variable
      $.get("http://ipinfo.io", function (response) {
        var usercity=response.city;
        console.log(usercity);
        $.ajax({
          //no need to provide url since we are making async call on the same page 
          type: "post",
          data: {cityinfo:usercity},
        });
      }, "jsonp");
    });
</script>

<?php
session_start(); 
$usercity=$_POST['cityinfo'];
echo $usercity; 
?>

Upvotes: 0

Views: 25

Answers (1)

Quentin
Quentin

Reputation: 944186

First, you make a regular request to the PHP page. $_POST['cityinfo'] is undefined at this stage because you don't set it. The page includes an error message telling you that.

Second, you make a JSONP request to ipinfo.io, and call a callback function when you get a response.

Third, you make a second HTTP request to the PHP page. This time you do define $_POST['cityinfo']. You have no success handler to do anything at all with the response so, although $_POST['cityinfo']; is set, you don't see any effect of that (unless you were to use the developer tools Network tab to examine the response itself).

It is important to note that this is a second, distinct request to the same URL. The JavaScript does not travel back through time and set the $_POST['cityinfo']; variable in the previous request (and it is the response to the previous request that is still displayed in the browser window).

Upvotes: 1

Related Questions