Sequenzia
Sequenzia

Reputation: 2381

Variables set in response of jQuery post request

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.

Upvotes: 2

Views: 3072

Answers (2)

Madbreaks
Madbreaks

Reputation: 19539

Just declare your variable outside of the $.post call:

var cID;
$.post('URL', function(data) {
    var cData = $.parseJSON(data);
    $.each(cData, function(k, v) {
        cID = v.id;  
    });
});

...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") $.post call, you can. From the docs for the asynch function parameter:

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

Cheers

Upvotes: 7

wirey00
wirey00

Reputation: 33661

You can store your whole data object instead of looping through and resetting the variable to a different value. Then you can access all your data outside. You should also define your variable outside of $.post so you have access to it

var cID;
$.post('URL', { }, function(data) {    
    cID = $.parseJSON(data);             
});

Upvotes: 1

Related Questions