James Bao
James Bao

Reputation: 23

How do I return a variable from $.post() in jQuery? Closure variable?

I am having trouble passing data retrieved from a $.post() function to use in other places in my code. I want to save the data as a variable and use it outside of the post() function. This is my code:

var last_update = function() {
$.post('/--/feed',
{func:'latest', who:$.defaults.login},
function($j){
            _j = JSON.parse($j);    
            alert(_j.text); // This one works    
        });
}
alert(_j.text); // This one doesn't
};

last_update(); //run the function

Please help!

Upvotes: 2

Views: 437

Answers (4)

user113716
user113716

Reputation: 322542

If you want to access the data value outside of the ajax request callback, you will need to place that code in a function, and call it from the success callback.

var last_update = function() {
$.post('/--/feed',
{func:'latest', who:$.defaults.login},
function($j){
            _j = JSON.parse($j);    
            alert(_j.text); // This one works   
            someOtherFunc(_j.text); 
        });
}
};

last_update(); //run the function

function someOtherFunc(val) {
    alert(val)
}

Essentially the same as placing the code in the callback, but can be useful if you have a bit of code that is reused elsewhere.

Upvotes: 1

Corey Ballou
Corey Ballou

Reputation: 43507

You could make your POST request synchronous and have a global _j variable:

// global!!!
var _j;

$.ajax({
  async: false,
  url: '/--/feed',
  data: { func:'latest', who:$.defaults.login },
  success: function($j) {
    _j = JSON.parse($j);    
    alert(_j.text); // This one works
  }
});

function last_update() {
  if (typeof _j != 'undefined') {
    alert(_j);
  }
}

Or you could simply call last_update() from within your success callback, thereby no longer requiring async:

$.ajax({
  url: '/--/feed',
  data: { func:'latest', who:$.defaults.login },
  success: function($j) {
    _j = JSON.parse($j);    
    alert(_j.text); // This one works
    last_update(_j);
  }
});

function last_update(_j) {
    alert(_j);
}

Upvotes: 0

Andy
Andy

Reputation: 17781

The $.post() AJAX call is asynchronous - this means that the AJAX request is made out-of-order of usual program execution, and in your program that means that the second alert is called before _j is populated. The order of execution is:

  1. call last_update()
  2. make the ajax request, remember to execute the callback function but not now
  3. call the second alert(_j.text);
  4. when the ajax request returns data, execute the callback function

Move the code that utilises the AJAX return data to the success() function (which is your return function function($j) here) - that what the success function is for.

$.post() is an aliased call to $.ajax() - full docs here.

Upvotes: 3

Fletcher Moore
Fletcher Moore

Reputation: 13814

Create _j in the scope of the last_update function.

Upvotes: -1

Related Questions