1
      var city;

      function getCity(){ 
         $.getJSON("http://ip-api.com/json/?callback=?", function(data) {
            city= data.city;
            alert(city);
         });
       }

       getCity();
       alert(city);

I am alerting the same city variable two times, one inside the function getcity() and another at last. But they both gives different values. Inside the function gives current city but out side the function gives undefined. I want to get current city on both.

1
  • 1
    ajax is asynchronous.... Commented May 22, 2016 at 12:30

2 Answers 2

4

AJAX is asyncronous.
That means that getCity will retrieve data at some later point but your script will not stop, and will trigger alert(city) which currelty holds no value (undefined)

Use a callback like:

function getCity( callback ){ 
  $.getJSON("http://ip-api.com/json/?callback=?", function(data) {
    var city= data.city;
    alert(city);
    callback( city );
  });
}


getCity(function( city ){
   alert(city);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Roko C. Buljan. This is what I want.
1

That's because $.getJSON is asynchonous; it will go and fetch the specified URL in the background, then run the function you pass to the second parameter when it is completed. Meanwhile, you can carry on doing other stuff while it is fetching the requested data.

This means that your control flow looks something like the following:

  • Declare city - value undefined.
  • Call getCity.
    • getCity will fire off the asynchronous request in the background.
    • getCity then exits.
  • Print out the contents of city - still `undefined.
  • At some point in the future, getJSON will have completed, and will call the specified function.
    • The callback will assign to city and print it out.

There's not really a nice way to ensure that city is set after getCity has executed - you should try and move your logic that requires city to be set inside the callback instead.

1 Comment

Thank You slugonamission for you explanation. It helped me to understand where i was wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.