Sumant
Sumant

Reputation: 964

getJSON success function out of scope

I just have started writing AJAX functions using jquery. Here i am calling myfunction(). where check.php is returning {"count":1} or {"count":0} for which myfunction is always returning retval=false . But for {"count":1} it should return true. I dont know where i am wrong. Below is the code i am using.

function myfunction(){
var retval=false;
if($('#tag').val() != ''){
    var query=$( "#tag" ).val();
    $.getJSON("check.php",{
        q: query
    },function(data){
        if(data.count==0){
            $('#formerrormsg').html('Error msg');
        }
        else{
            retval=true;
        }
    });
}
return retval;
}

Please Help me to understand this.

Upvotes: 0

Views: 300

Answers (2)

UltraInstinct
UltraInstinct

Reputation: 44444

That is because, $.getJSON(..) is asynchronous. The below is what jQuery doc says about the third parameter you are passing (function(data){...}):

success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.

The function which set retval to true is executed when the AJAX call succeeds; not when you call myfunction()

There are two way you could get around this:

  • Make your AJAX call synchronous; the function wont return until the response is received. (Not a great idea, UI might freeze)
  • Modify your code -- the asynchronous way. Typically, call the function (that would ideally be depending on the return value) from within the "success-function" defined as the 3rd parameter.

Upvotes: 2

rae1
rae1

Reputation: 6144

It is an AJAX (asynchronous) request so return retval; is returning before the AJAX success function executes, hence always returns false. You need to change your implementation to wait for that request before returning and using retval.

Upvotes: 0

Related Questions