jQuery ajax problems with success trigger
I know what my problem is, I just cannot work out the solution.
I have a wizard which basically is a 5 page form. On each page I do various validation, if the validation matches a 'page' is hidden and the next page is shown.
$('#wizard-2 .continue').click(function() {
// Validation Here
$('#wizard-2').hide();
$('#wizard-3').show();
});
My problem is that one of the validation functions requires an ajax call.
$.ajax({
// Misc stuff
success : function (bool) {
if (bool == 0) {
// Show Error
return false;
}
}
});
What I need to happen is the script waits for the ajax call to complete and if the success function returns false then it needs to stop the script.
If I was using a real form I would put form submit in the success function and prevent the default action directly after the ajax. Obvio开发者_JAVA百科usly this wouldn't work here as the form shouldn't be submitted until the final page of the wizard is completed.
Any ideas?
AJAX is asynchronous; you can't do that.
Technically, you can, but it will freeze the browser; don't.
You should change your validator to take a callback instead of returning a bool:
function validate(callback){
$.ajax({
success : function (bool) {
if (bool == 0) {
//Do soemthing
callback(false);
} else
callback(true);
}
});
}
I would try this way:
1) Define a function to perform the validation which also expects a parameter of type function for the callback.
2) In the click event call the validation function with the function that should be executed on success event.
Something like:
$('#wizard-2 .continue').click(function () {
// Validation Here
processWizard(function(){
$('#wizard-2').hide();
$('#wizard-3').show();
});
});
function processWizard(callback){
$.ajax({
// Misc stuff
success : function (bool) {
if (bool == 0) {
// Show Error
return false;
}
else{
callback();
}
}
});
}
You can try inside your .ajax call to set async: false
to prevent the call from occurring asynchronously. This will slow your page down, of course, but is one option.
The other option is to put the stuff after the validation that does the ajax call in a function which you call in success. Not knowing what it is I can't sketch out an exact option, but certainly
$('#wizard-2').hide();
$('#wizard-3').show();
would be part of it.
Can you put your hiding/showing code inside the callback function for that success AJAX call? So, only if that returns successful will it show the next page in the 'form'.
Essentially, AJAX is an asynchronous call, so your best way to have something occur when the call returns is to either place it in or call it from the callback function.
精彩评论