Submit form if ajax validator returns true using jquery
I am not sure where I'm going wrong. The idea is that before the form is submitted, one of the input fields is sent to a server-side validator via ajax. If the response is 1, the input is valid and the form should be submitted. If the response is 0, the form should not be submitted. The issue is that I can't figure out how to set a variable within the ajax request function that will prevent the form from being submitted. This is what I have:
$("#form").submit(function() {
var valid= false;
var input = $("#input").val();
$.ajax({
type: "POST",
url: "validator.php",
data: "input=" + input,
success: function(msg){
valid = (msg == 1) ? true : false;
if(!valid) {
$("#valid_input").html("Please enter valid 开发者_StackOverflowinfo");
} else {
$("#valid_input").html("");
}
}
});
return valid;
});
The problem is that the $.ajax
request is asynchronous and takes a while to complete. Therefore the function carries on and returns false before the success function is event executed.
To solve this you could add async: false
to you settings for the AJAX call, but this would suspend execution until the AJAX call returns.
Another solution would be to create a hidden input in the form called valid
:
<input type="hidden" name="valid" value="false" />
Then within the submit function but before the ajax call create a reference to the from var $form = $(this)
. Then if the AJAX call returns valid change the value of this hidden input, and submit the form again:
$('input[name="valid"]').val('true');
$form.submit();
And then at the end of the submit function only return false if the value of the hidden input is true:
if ($('input[name="valid"]').val() == 'false') {
$.ajax({ ... }); // changes the value of the hidden input from false to true
return false;
}
The success function runs when the HTTP response arrives so valid
will always be false.
Call the form's .submit()
method if it is valid (and make sure you don't have a form control with the name or id submit as that will clobber the method).
this is assuming that you have loaded the ajax validate plugin and the ajax form plugin, http://malsup.com/jquery/form/
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
the example below will make all forms with class "ajaxForm" validate and then if valid submit via ajax...
$( document ).ready( function(){setupForms();} );
function setupForms(){
var ajaxOptions = { beforeSubmit:checkForm,
success:function(){
// the ajax was successful
}
};
$( '.ajaxForm' ).ajaxForm( ajaxOptions );
$( '.ajaxForm' ).validate();
}
function checkForm(data,form){
var valid = $(form).valid();
return valid;
}
精彩评论