in my script i have an ajax call to a php file and i would like to have the call completed before the rest of the script below gets executed
Here is the script i am referring to:
function game_settings(state){
if(state == "load"){
ui.load_game();
//do ajax call to load user last save
var dataString = {"user_data": "true"};
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data: dataString,
dataType: 'JSON',
success: function(success) {
player_details_init(success)
},
error: function(){
alert("ERROR in User data");
}
});
console.log (player_level);
//scene.load("level_"+level);
//instantiate a heroObject
player = new Player(20,20,game_width, game_height);
// set it's image to the proper src URL
player.image.src = "images/Mage_Sprite.png";
// once the image has completed loading, render it to the screen
player.image.onload = function()
{
player.render();
};
lastUpdate = Date.now();
}
SO for instance right now when the script runs, i can see in console that the ajax request gets made, and then the rest of the script gets execute before the ajax has finished resulting in this call:
console.log (player_level);
to return undefined rather then the value it should be because the ajax hasn't completed.
To clarify my question is:
How should i make the ajax call finish before the rest of the script gets processed?
Thanks
You can either put the rest of the script in the success callback of the AJAX call, or set the async
property of the AJAX call config to false, which will make it synchronous.