1

I want a JavaScript function that posts to a php, and returns the value, so that calling the function from another function in JavaScript gives me the value. To illustrate better please look at my current code:

function sumValues(number1, number2) {
    var return_val;
    $.post("sum_values.php", {number1: number1, number2: number2},
    function(result) {
        return_val = result;
    });

    return return_val;
}

However, the above is returning undefined. If I put alert(result) inside the function part in $.post, I can see the result. However if I call the function from another JavaScript file the return value return_val is 'undefined'. How can I put the result from $.post inside return_val so that the function can return it?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
luqita
  • 4,008
  • 13
  • 60
  • 93
  • 3
    You can't, you need to provide a callback. This is asynchronous. This is a duplicate, I just need a few seconds to find a question. – davin Sep 25 '11 at 13:04
  • Other almost identical questions: http://stackoverflow.com/questions/3732258/why-can-i-not-return-responsetext-from-an-ajax-function http://stackoverflow.com/questions/290214/in-ajax-how-to-retrive-variable-from-inside-of-onreadystatechange-function http://stackoverflow.com/questions/1955248/how-to-return-variable-from-the-function-called-by-onreadystatechange-function http://stackoverflow.com/questions/562412/return-value-from-function-with-an-ajax-call – davin Sep 25 '11 at 13:15

2 Answers2

5

AJAX is asynchronous meaning that by the time your function returns results might not have yet arrived. You can only use the results in the success callback. It doesn't make sense to have a javascript performing an AJAX request to return values based on the results of this AJAX call.

If you need to exploit the results simply invoke some other function in the success callback:

function sumValues(number1, number2) {
    $.post("sum_values.php", { number1: number1, number2: number2 },
    function(result) {
        callSomeOtherFunction(result);
    });
}

and inside the callSomeOtherFunction you could show the results somewhere in the DOM.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

$.post is asynchronous by default (docs). You could either pass the async:false option (blocks the browser, not a good user experience) or you should consider using callback functions (better IMHO).

function sumValues(number1, number2,callback) {
$.post("sum_values.php", {number1: number1, number2: number2},callback);
}

sumValues(1,3,function(result){ 
    doSomething(result); 
});
Maximilian Hils
  • 6,309
  • 3
  • 27
  • 46