Reputation: 153
I am working on a html contact form and using the javascript code below to validate the form when the submit button is clicked:
function leftValue(e, t, n) {
$(this).text(t.parent()[0].style.left)
}
$(document).ready(function() {
required = ["name", "email"];
email = $("#email");
errornotice = $("#error");
emptyerror = "Required Field";
emailerror = "Required Field";
$("#contact-us").submit(function() {
for (i = 0; i < required.length; i++) {
var e = $("#" + required[i]);
if (e.val() == "" || e.val() == emptyerror) {
e.addClass("form-error");
e.val(emptyerror);
errornotice.fadeIn(750)
} else {
e.removeClass("form-error")
}
}
if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA- Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("form-error");
email.val(emailerror)
}
if ($(":input").hasClass("form-error")) {
return false
} else {
errornotice.hide();
return true
}
});
$("input").focus(function() {
if ($(this).hasClass("form-error")) {
$(this).val("");
$(this).removeClass("form-error")
}
})
});
HTML
<form action="" method="post" name="contact-us" id="contact-us">
<input type="text" id="name" name="name"/>
<input type="text" id="email" name="email"/>
</form>
<div id="success">Thank you for your message!</div>
Once the validation is passed and the submit button is clicked again, the data is posted via PHP and emailed using this code:
<?php
if(isset($_POST['submit']))
{
$to="[email protected]";
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$body="Name: $name \n\n Email Address: $email \n\n";
$sent=mail($to, $body);
}
?>
I am trying to now using ajax to carry out these functions and display a confirmation message on the same page without reloading. I have tried the code below which allows the form to be validated but when the validation passes and submit is clicked again, the page just reloads and doesn't display the confirmation message contained in the #success div?
$(document).ready(function() {
$("#contact-us").submit({
submitHandler: function() {
$.post("<?php echo $_SERVER[PHP_SELF]; ?>", //post
$("#contact-us").serialize(),
function(data){
if (data == 'Sent') {
$("#success").fadeIn();
}
//
});
return false;
}
});
});
Upvotes: 0
Views: 550
Reputation: 2359
Did you try this: event.preventDefault();
$(document).ready(function() {
$("#contact-us").submit(function(event) {
event.preventDefault();
$.post("<?php echo $_SERVER[PHP_SELF]; ?>", //post
$("#contact-us").serialize(),
function(data){
if (data == 'Sent') {
$("#success").fadeIn();
}
});
return false;
});
});
Upvotes: 0