Reputation: 83053
I have a form validation method that's called on submit. It executes a "get" to validate one of the fields, and returns false if the field is invalid:
$.get('validate.cfc',
{
method: 'validateUserID',
userID: $('#userID').val(),
returnformat: 'plain'
},
function(data){
if($.trim(data) == 0){
alert('Invalid userID!');
return false;
}
}
);
It then goes on to do a few further simple validation steps (without an ajax call). For example:
if(!isDate($('#endDate').val()) && $('#endDate').val() != ""){
alert("Please enter a valid end date");
return false;
}
The problem is that the code continues while the get
executes. So if the userID is not valid and the end date is not a date, first the "Please enter a valid end date" message shows up, and then the "Invalid userID!" message. How can I get my code to wait till the get is finished?
(The only thing I can think of is to put a small setTimeOut around all the rest of the code in the function after the get... not the most elegant solution.)
Upvotes: 0
Views: 268
Reputation: 1163
There is an async property to send as part of your jquery ajax request, just set it to false.
Although they say in new versions it is deprecated, I have used it before and it worked. Not sure what the new syntax is. . . or if it is
see http://api.jquery.com/jQuery.ajax/
Upvotes: 0
Reputation: 74
If I get it right, then this should do it:
$.get('validate.cfc',
{
method: 'validateUserID',
userID: $('#userID').val(),
returnformat: 'plain'
},
function(data){
if($.trim(data) == 0){
alert('Invalid userID!');
return false;
}else{
if(!isDate($('#endDate').val()) && $('#endDate').val() != ""){
alert("Please enter a valid end date");
return false;
}else{
submit the form
}
}
}
);
Upvotes: 1