views:

29

answers:

3

I think my program is skipping result of JSON call. Is it possible to make a closure function here or make the program wait for JSON call to return?

function username_not_duplicate(username) {
   var function_name = "get_username";
   var parameters = [username];
   var url = "/get_functions.php?function_name=" + function_name + "&parameters=" + parameters;
   $.getJSON(url, function(user_name) {
      if (user_name == true) {     
         return true;
      }
   });
   return false;
}
A: 

Yeap, username_not_duplicate just returns false immediately because getJSON is asynchronous (ie non-blocking). The return true statement just returns true from the response handler. Normally, you shouldn't do such a blocking calls you're trying to achieve. I suppose you can consider remembering of a state of the request somewhere globally.

eigenein
can i make getJSON non synchronous?
bob
@bob -- nope. Would be a good option for jQuery to add though.
Drew Wills
@bob `$.getJSON` is a simply shorthand of an equivalent `$.ajax` function, which allows to send synchronous requests. See `async` setting at http://api.jquery.com/jQuery.ajax/ . So... the answer is 'yes, not `$.getJSON` but `$.ajax`'
eigenein
+1  A: 

The $.getJSON() API call is asynchronous. You can make it synchronous by converting to $.ajax()...

function username_not_duplicate(username) {
   var function_name = "get_username";
   var parameters = [username];
   var url = "/get_functions.php?function_name=" + function_name + "&parameters=" + parameters;
   var rslt = false;
   $.ajax({
     async: false,
     url: url,
     dataType: "json",
     success: function(data) {
       if (data == true) {     
         rslt = true;
       }
   });
   return rslt;
}
Drew Wills
beauty! i will try this!
bob
A: 

Drew's answer is nearly perfect, just missing one bracket and comma for IE.

function username_not_duplicate(username) {
   var function_name = "get_username"; 
   var parameters = [username]; 
   var url = "camps/includes/get_functions.php?function_name=" + function_name + "&parameters=" + parameters;
   var rslt = false; 
   $.ajax({ 
         async: false, 
         url: url, 
         dataType: "json", 
         success: function(data) {
           if (data == true) {                   
             rslt = true; 
           }
        }, 
    });
    return rslt; 
}
bob