I have a jQuery callback function. In that function I want it to change the value of a variable that is in a higher scope, but for some reason it is not doing that. Here is the code:
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=');
}
}
The problem is that
$.post()is asynchronous, so thatreturnedData.my_id = 5;happens after youralert()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: