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 c开发者_开发问答ode:
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 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.
$.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);
});
精彩评论