Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the jQuery $.post return data to a JavaScript variable

Tags:

jquery

ajax

php

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.

like image 812
CptSpike Avatar asked Sep 23 '26 18:09

CptSpike


1 Answers

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
});

http://jsfiddle.net/C4JnU/1/

like image 51
Rafay Avatar answered Sep 26 '26 06:09

Rafay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!