views:

38

answers:

3

Hello, I have a jquery callback function. In that function I want it to change the value of a varible that is in a higher scope, for somereason it is not doing that. Here is the code.

Thanks

function add() {
    var returnedData = {
        my_id: 0
    };

    $.post("add_event.php", { event : toSendText }, function(data) {
        returnedData.my_id = 5;
    }, "json");

    if(add_page == true){
        alert(returnedData.my_id);
        window.open('content-list.php?cal_id=');
    }
}
+2  A: 

The problem is that $.post() is asynchronous, so that returnedData.my_id = 5; happens after your alert() does (the data comes back from the server at some point later, when the request finishes).

To make this work like you want, you need to continue working in the callback once your data is available, like this:

function add() {
  $.post("add_event.php", { event : toSendText }, function(data) {
     if(data.add_page == true) {
       //use data in some way here presumably
       window.open('content-list.php?cal_id=' + data.id); //maybe this?
     }
  }, "json");
}
Nick Craver
A: 
jQuery.ajax( settings )

async Boolean Default: true

By default, all requests are sent asynchronous (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.

http://api.jquery.com/jQuery.ajax/

The jQuery.post( settings ) by default doesn't pass the parameter async so it assumes true

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success
  dataType: dataType
});

http://api.jquery.com/jQuery.post/

BrunoLM
A: 

Thank you both, I changed from .post to .ajax, and set the async to false, and everything works.