5

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.

4 Answers 4

6

The function you passed into $.getJSON() is the callback run when the function completes successfully. All else being equal, stick the "rest of it" inside that method. If you can't do so, what you're after is called a jQuery Deferred. See http://www.erichynds.com/jquery/using-deferreds-in-jquery/ and http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ for code that looks like so:

var req = $.getJSON('blah', 'de', 'blah');

req.success(function(response){
    // The request is done, and we can do something else
});
2
  • I want the main function to return either a 'true' or a 'false', this does not seem to work inside the success method. Is this possible or am I making a mistake(while coding) implementing this Apr 28, 2012 at 8:05
  • It is bad form to synchronously wait for an async method. Your main function could return the deferred and callers could also subscribe to its completion.
    – robrich
    Apr 28, 2012 at 17:14
5

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');
}
6
  • the go123(function(result) that you have written outside the function what is that ? and should it end with a semicolon ? Apr 28, 2012 at 8:19
  • @Yasser the go123(function(result){...}) calls the go123() function, passing it a "callback" function that gets executed once getJSON receives it's reply. And yes, there should be a ; after the call. It's optional, but for best practice, it should be there.
    – Joseph
    Apr 28, 2012 at 8:22
  • what I understand is that I can now move my json to a fucntion go123 and now I can have another function say abc where I will write the second set of (go123(function(result){) code right ? Apr 28, 2012 at 8:29
  • @Yasser yes, sort of. To put this to simpler terms, your "JSON fetcher" is go123. When you need data from it, you call it. If you want to do something with the data returned, pass it a callback which operates on that data.
    – Joseph
    Apr 28, 2012 at 8:33
  • I am now using a method called goBefore123() where in I am using this second piece of code but I still am not able to return true/false frm the method ? Could I be doing something wrong ? Apr 28, 2012 at 8:51
3

Calling an external url will take too much time, wait for the result Check below

var jqxhr = $.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

http://api.jquery.com/jQuery.getJSON/

1
  • I want the main function to return either a 'true' or a 'false', this does not seem to work inside the success method. Is this possible or am I making a mistake(while coding) implementing this Apr 28, 2012 at 8:18
-1

.success

http://api.jquery.com/jQuery.getJSON/

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.