Wait for Json call to be completed in javascript
javascript, json
Solution
AJAX calls are asyncrhonous. They don't wait for the reply. They operate in the background and execute the code that follows it immediately after the call. Therefore, the data received in `getJSON` is not yet there when the operations below it are executed.
You can put the operations you want in the callback so that they get executed when the data is revceived:
function go123(callback){
var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
//execute the callback, passing it the data
callback(data);
});
}
//when you call go123, it get's back the result:
function goBefore123(){
//get our JSON
go123(function(data){
//when we get our data, evaluate
if (data.properties.city != null){
cityName = data.properties.city;
check = true;
alert('executed after returned');
afterCall();
} else {
cityName = "NaN"
}
});
alert('i am executed before anything else');
}
function afterCall(){
alert('im also executed after');
}
Problem
I am using the below json call in my javascript method ``` function go123(){ var cityName = ""; var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) { if (data.properties.city != null){ cityName = data.properties.city; check = true; } else { cityName = "NaN" } }); // end of my Json Call. // my validation is done below if(cityName != "NaN"){ return false; } else { // here I except the cityName to not be "" but be some value which is set as :cityName = data.properties.city; return true; } } // end of my function ``` Now what problem I am facing is that before my Json call is compelete the next set of statements ( in the code below the line "// my validation is done below " ) is already executed. I want to get the values set in my json call (cityName) and only once when the call is completed then only I want the next set of statements to be executed. Please help me on this. Any advice/ideas/suggestions will be highly appreciated ! Thanks.