Reputation: 964
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
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:
Upvotes: 2
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