Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  22] [ 6]  / answers: 1 / hits: 26595  / 9 Years ago, tue, june 30, 2015, 12:00:00

I'm trying to get user's city and country before moving on with my code. It seems as if javascript is not executed in the order I need.



$(document).ready(function() {    
var country, city = '';

function geoData() {
$.getJSON('http://ipinfo.io/json?callback=?', function (data) {
console.log('step 1');
country = data.country;
city = data.city;
console.log('step 2');
});
};

geoData();
console.log('step 3');

/* rest of the code */
});


I want the code to be executed as:



step 1
step 2
step 3


However when I run the script I get:



step 3
step 1
step 2


Why is the code running in an asynchronous way? Any suggestions how I can fix it?



Thanks.


More From » jquery

 Answers
60

AJAX requests are asynchronous - it's what the first A stands for. If you have logic that depends on the data returned by the request, it needs to be placed within the callback function. Try this:



var country, city = '';

function geoData() {
$.getJSON('http://ipinfo.io/json?callback=?', function (data) {
console.log('step 1');
country = data.country;
city = data.city;
console.log('step 2');

step3();
});
};

function step3() {
console.log('step 3');
}

geoData();


An alternative is to use a promise, although the logic flow is roughly equivalent:



var country, city = '';

function geoData() {
return $.getJSON('http://ipinfo.io/json?callback=?', function (data) {
console.log('step 1');
country = data.country;
city = data.city;
console.log('step 2');
});
};

var deferred = geoData();
$.when(deferred).done(function() {
console.log('step 3');
});

[#65981] Sunday, June 28, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tai

Total Points: 466
Total Questions: 87
Total Answers: 116

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;