Reputation: 5986
I have a pretty complicated function which does a couple of AJAX posts on submitting a form, to verify values. Depending on the values returned from the POSTs the submit should either work or fail. I thought this could be done using a global boolean and setting its value to either true or false throughout the function, then checking at the end if the boolean had been changed to 'true' and if so call 'return false;'.
This is failing though. I've read up around it and I think it's because the AJAX call is asynchronous so the code isn't executed in sequence.
My code is like this:
$('.to-step-3').click(function(){
var shape = '';
blnError = false;
$.post('/base/RoomBuilder/GetRoomShape.aspx', function(data) {
if(data.substring(0,5) == 'Error'){
alert(data);
blnError = true;
}else{
shape = data;
$.post('/base/RoomBuilder/GetRoomDimensions.aspx', function(data2) {
if(data2.substring(0,5) == 'Error'){
alert(data2);
blnError = true;
}else{
var arrDims = data2.split('_');
var l = arrDims[0];
var w = arrDims[1];
var sl = arrDims[2];
var ll = arrDims[3];
var sw = arrDims[4];
var lw = arrDims[5];
var failMessage = 'Please enter all required dimensions to build your room';
switch(shape) {
case 'square':
if(!(notNullOrEmpty(l))){
alert(failMessage);
blnError = true;
}
break;
case'rectangle':
if(!(notNullOrEmpty(l)) || !(notNullOrEmpty(w))){
alert(failMessage);
blnError = true;
}
break;
case'lshaped':
if(!(notNullOrEmpty(sl)) || !(notNullOrEmpty(ll)) || !(notNullOrEmpty(sw)) || !(notNullOrEmpty(lw))){
alert(failMessage);
blnError = true;
}
break;
case'lshapedalt':
if(!(notNullOrEmpty(sl)) || !(notNullOrEmpty(ll)) || !(notNullOrEmpty(sw)) || !(notNullOrEmpty(lw))){
alert(failMessage);
blnError = true;
}
break;
}
}
});
}
});
if(blnError == true){
return false;
}else{
return true;
}
});
I found an example of something similar jquery - return value from callback function (in post request) into the function its inside of? but am struggling to get my head around it in the context of what I need to do (I'm admittedly not great at Javascript!)
Could anyone please point me in the right direction here as I've been staring at this way too long! Thanks all.
Upvotes: 1
Views: 2192
Reputation: 13853
The simplest way to solve your problem would be to just make it a synchronous call,
$.ajaxSetup({async: false});
$.post(..);
$.ajaxSetup({async: true});
Upvotes: 0
Reputation: 69905
jQuery post
is async by nature so before the ajax response comes the if
condition has already been executed. If you want to make execution wait untill ajax response comes then you can use jQuery ajax
setting async property to false. Try this
$.ajax({
url: '/base/RoomBuilder/GetRoomDimensions.aspx',
async: false,
type: 'post',
success: function(){
//Your logic here
}
});
//Now check the condition here
if(blnError == true){
return false;
}else{
return true;
}
Upvotes: 1