I have a form which am using html5 to validate for email and required fields. The form is to be submitted via ajax. How do i determine that the form passed validation before i allow to form to submitted via ajax.
This is my html:
<form action="" method="post" id="comment_form">
<input type="hidden" name="post_id" value="<?=$post->ID ?>" />
<label for="name">Name</label>
<input type="text" name="name" required="required">
<label for="email">Email Address</label>
<input type="email" name="email" required="required">
<label for="comment">Comment</label>
<textarea name="comment" required="required" >
</textarea>
<label for="submit"></label>
<button type="submit"class="button green meduim" id="comment_btn">Submit</button>
</form>
This is my jquery
$("#comment_btn").click(function(e){
//the request url
var url = site_url+'comments/post_comment';
//cross site request forgery token
var xtoken = $("input[name='xtoken']").val();
//post data
var dataObj = {
"name":$('#name').val(),
"email":$("#email").val(),
"comment":$("#comment").val(),
"post_id":$("input[name='post_id']").val(),
"xtoken":xtoken
};
//dim form
$('#comment_form').addClass('dim');
//make request
$.ajax({
url:url,
type:'POST',
data:dataObj,
dataType:'json',
error:function() {},
success:function(resp) {
if(resp.status == "ok")
{
$('#comment_form').removeClass('dim');
}else {
alert("An error was encountered");
}
}
});
e.preventDefault();
});
Is there a way to determine if the form is validated?
Don't bind to the click event of the submit button simply bind to the submit event of your form:
$('#comment_form').submit(function(e){
e.preventDefault();
//submit via ajax
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With