Francesco Francesco - 5 months ago 89
Javascript Question

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.