Sunday, 27 November 2016

javascript - jQuery: Return data after ajax call success




I have something like this, where it is a simple call to a script that gives me back a value, a string..



function testAjax() {
$.ajax({

url: "getvalue.php",
success: function(data) {
return data;
}
});
}


but if I call something like this




var output = testAjax(svar);  // output will be undefined...


so how can I return the value?
the below code does not seem to work either...



function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {


}
});
return data;
}

Answer



The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response.



You can pass in a callback function that handles the result:




function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}



Call it like this:



testAjax(function(output){
// here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...