I use the jQuery post requests a lot. I understand that when you are working within the response the variables have their own scope. Is there a good way to set variables in the response but have those variables available outside of the post? Like for other functions in JS.
Here is a sample of what I am doing:
$.post('URL', { }, function(data) {
var cData = $.parseJSON(data);
$.each(cData, function(k, v) {
var cID = v.id;
});
So what I do that I cannot access cID outside of the post request. Is there a way to make this work?
Any help would be great.
Thanks
UPDATE:
Here is a sample I just tested:
var savedCount;
$.post('/app/actions/countsAction.php', { call: "getCountFullByID", countID: countID}, function(data) {
savedCount = 1;
alert(savedCount);
});
alert(savedCount);
I get 2 alerts when I run this. The first one is a 1 when the alert is fired off in the $.post and the second one is undefined.
Just declare your variable outside of the
$.postcall:…not sure what you’re attempting to do with that though, as you’re looping over a collection and continually (re)setting the value of a single variable. If you need to keep track of all the variables, consider holding the values in (maybe) an Array.
EDIT
If you need to do a synchronous (“blocking”)
$.postcall, you can. From the docs for theasynchfunction parameter:Cheers