views:

788

answers:

3

I am quite on lost on why Javascript does certain things in this way, or maybe I coded something wrong. But how come the code after $.getJSON gets executed before the callback is complete?

window.ratingCallback = function(data){

     if(data[0].code == 3){  
         ratingHTML = buildHTML(0);
         console.log('a'+ratingHTML);
         return;
     }

     ratingHTML = buildHTML(data[0].rating);
     console.log('b'+ratingHTML);
     return;
 };

  function buildHTML(pageRating){

     for(counter = 1; counter <= 5; counter++){

      if(counter == pageRating){
              ratingHTML += '<input name="star1" type="radio" class="star" value="'+counter+'" checked="checked"/>';
      } else {
              ratingHTML += '<input name="star1" type="radio" class="star" value="'+counter+'"/>';    
      }
     }

     return ratingHTML;
 }


$.getJSON("https://domain.com/"+data+"?jsoncallback=?");

console.log(ratingHTML+"WHY DOES THIS EXECUTE FIRST AND NOT AFTER THE CALLBACK SINCE IT IS PLACED AFTER getJSON????");

The reason I want this to be different is that I need ratingHTML to be a global variable.

I understand that the callback gets called when the remote server has given a response, but can I let the rest of the script wait with further execution? Without placing all code in the callback function or any function?

Thank you very much!

Ice

+6  A: 

The getJSON() call is asynchronous.

It's even mentioned in the docs (http://docs.jquery.com/Ajax/jQuery.getJSON):

Note: Keep in mind, that lines after this function will be executed before callback.

M4N
+4  A: 

getJSON is an asynchronous method which basically means when you call it, it returns to the main program flow immediately. So it is "non blocking." You should put your console.log into the callback method if you want it to log after getJSON is done. Or if you don't want to follow the callback pattern and you want your call to be synchronous, use the ajax call and set the async option to false. Be aware though, this will cause the browser to block, or appear to be frozen while it gets the data.

Bob
+3  A: 

AJAX requests are usually done asynchronously (the first A in AJAX). This means that the request will start, then it will carry on with the code it was executing without waiting for the request to return.

If you want it to wait you can set requests to synchronous mode, but I'm not sure how to do that in jquery.

Greg