Reputation: 23
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
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
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
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:
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