jQuery Validator fails to submit with custom method using ajax
So I have a custom validator checking an inputted zipcode against my database of acceptable zip codes.
My custom method is as follows:
jQuery.validator.addMethod("validZip", function(value, element){
var _id = $(element).attr("id");
$.post(
'/xpress/wp-admin/admin-ajax.php',
{action:"test_checkZip", zip:value},
function(response){
if (result == 0){
return false;
} else {
return true;
}
}
);
}, '*');
The problem, I believe, is that since ajax is non-blocking the latency of the request doesnt return the true/false result for the validator in time for it to be recognized.
Whenever the result should be true, it fails to hide the error message and the form fails to ever be submittable.
I've been able to hide the error message in the return true code block by explicitly hiding the error element. The error message does hide, however, the form still returns false since the custom method fails to ever return true.
Have I done something wrong? How can I get around this issue?
Many thank开发者_JAVA百科s.
You could use a synchronous recuest using $.ajax
jQuery.validator.addMethod("validZip", function(value, element){
var _id = $(element).attr("id");
var return_val = null;
$.ajax({
url: '/xpress/wp-admin/admin-ajax.php',
type: 'post',
data: {action:"test_checkZip", zip:value},
async: false, //This does the trick
success: function(response){
if (result == 0){
return_val = false;
} else {
return_val = true;
}
}
});
return return_val;
}, '*');
Hope this helps. Cheers
If you use $.ajax()
instead you can specify the POST to be made synchronously instead of async.
$.ajax({
url: '/xpress/wp-admin/admin-ajax.php',
type: 'POST',
data: {action:"test_checkZip", zip:value},
async: false,
success: function(response){
// Process response..
}
});
精彩评论