Submit form if ajax validator returns true using jquery
- by Anthony
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 info");
} else {
$("#valid_input").html("");
}
}
});
return valid;
});