I’m wanting to run AJAX to get some URL data, build an object from the data and assign it to a global object variable. So I know I need to run a synchronous ajax request. (Right?) Well I also want to make use of the beforeSend setting to give my users a loading screen. (I probably should be asking first, is beforeSend the only way to achieve that?) How might I combine the benefits sync and async?
async:
$.ajax({
url:'scripts/scripts.php?call=page&url='+thisurl, /*local*/
dataType:'html',
beforeSend:function(){
$('#display').html('<div class="loading"></div>');
},
success:function(data, textStatus, jqXHR){
/*local*/ myobj = getMyObj(data); $('#display').html(myobj);
},
error:function(jqXHR, textStatus, errorThrown){ }
});
sync:
$.ajax({
url:'scripts/scripts.php?call=page&url='+thisurl, /*local*/
dataType:'html',
async:false,
success:function(data, textStatus, jqXHR){
/*global*/ myobj = getMyObj(data);
}
});
$('#display').html(myobj);
sorry if this doesn’t make sense
Ehm, well, it’s pretty obvious that if you want to display something before a synchronous ajax function you do:
On the other hand why use a synchronous Ajax function, it’s a really bad idea, use promises instead, or something like:
Or stick the ajax in a seperate function and run that the same way, there are many options other than synchronous Ajax calls!