Scope Of Javascript Variable
Possible Duplicate: return from a function ajax JavaScript asynchronous return value / assignment with jQuery How do you output the data variable to the second alert statement.
Solution 1:
You can't.
AJAX is asynchronous. The response is not available until some time later.
The jQuery.post
call will begin the AJAX request, and return the jqXHR object which is handling the request. The script will continue to be executed (alert(test)
will fire next), and then some time later when the AJAX request has completed (i.e. the HTTP response is received), the callback:
function(data) {
alert(data)
test = data;
}
will be executed.
Solution 2:
If you are strict with scenerio, define test variable in global scope, in that way you can use it anywhere in your code.
Solution 3:
Try this way :
var test;
$.post("index.ajax.php", { lookup:value },
function(data) {
alert(data)
test = data;
})
functionalertTest(){
if(test != undefined) {
alert(test);
clearInterval(t);
}
}
var t = setInterval(alertTest, 1000);
You will get test value when ajax request is completed and test is assigned
Post a Comment for "Scope Of Javascript Variable"