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?
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
successcallback. 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
successcallback:and inside the
callSomeOtherFunctionyou could show the results somewhere in the DOM.