Reputation: 33
I have the following jQuery
code in my HTML page:
$.post("MyPHP.php", {category: CATEGORY}, function(data){var test = data;});
But I can't seem to use test anywhere else in my page. I know this is AJAX
so I have to wait for $.post
to complete but the variable test is never set. If I instead use the return data to change the innerhtml of a paragraph, the paragraph updates after a small delay.
Any thoughts?
EDIT: Cracked it! You can call another function from the $.post
return function, ie: function(data){setVar(data)});
and simply define the setVar(data)
function as follows:
function setVar(data){test = data;}
Provided test has already been defined in global scope var test;
you can use it through out the rest of your code.
Upvotes: 3
Views: 1228
Reputation: 31043
because the scope of your var is limited try moving your test variable to a much global scope
var test;
$.post("MyPHP.php", {category: CATEGORY}, function(data){
test = data;
});
ajax requests are asynchronous so you will never know when it is complete unless you put your variable in the success callback (which) you did or you can make the ajax request synchronous (plz dont do that) or you can use .when
to make sure that your ajax call dependent code is executed when all the variables are set.
see this demo even if you move the test variable to the global scope it still logs undefined
to the console so try
var test;
var x=$.post("MyPHP.php", {category: CATEGORY},, function(data){
test = data;
});
console.log(test);// still undefined
$.when( x ).then(function(args){
console.log(test);// your var is set
});
Upvotes: 1
Reputation: 64536
You have declared your test
variable within the ajax success function, therefore its scope is limited to the success function. If you want to access it from other code you can declare it in the global scope, and just overwrite it in the success function.
var test; // delcared in global scope
$.post("MyPHP.php", {category: CATEGORY}, function(data){ test = data;});
Upvotes: 0