I am trying to use ajax and jQuery to process a form, fade out the form and then fade in with a success or error message. Unfortunately for some reason the form is still submitting normally instead of using ajax. I am using the jQuery validation plugin to validate the form. Here is the code.
HTML
<form name="contact" id="contact" method="post" >
<div class="form-group">
<label for="name" class="control-label">Your Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="email" class="control-label">Email Address:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email">
</div>
<div class="form-group">
<label for="message" class="control-label">Enter Your Message:</label>
<textarea class="form-control" name="message" id="message" rows="3" placeholder="What's up?"></textarea>
</div>
<button type="submit" name="submit" class="btn button btn-default">Submit</button>
</form>
<div id="success">
<span>
<p>Your message was sent succssfully! I will be in touch as soon as I can.</p>
</span>
</div>
<div id="error">
<span>
<p>Something went wrong, try refreshing and submitting the form again.</p>
</span>
</div>
JS
$(function(){
$('form').validate({
rules: {
name:{
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
message:{
required: true,
minlength: 10
}
},
highlight: function (element, errorClass) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element, errorClass) {
$(element).closest('.form-group').removeClass('has-error');
},
submitHandler: function(form) {
var name = $('input#name').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
var dataString = ' name= ' + name + ' &email= ' + email + ' &message= ' + message;
// alert(dataString);
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"process.php",
success: function() {
$('#contact :input').attr('disabled', 'disabled');
$('#contact').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#success').fadeIn();
});
},
error: function() {
$('#contact').fadeTo( "slow", 0.15, function() {
$('#error').fadeIn();
});
}
});
}
});
});
PHP
<?php
$to = "[email protected]";
$from = $_REQUEST['email'];
$name = $_REQUEST['name'];
$headers = "From: $from";
$subject = "You have a message.";
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"phone"} = "phone";
$fields{"message"} = "message";
$body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$send = mail($to, $subject, $body, $headers);
?>
You need to stop the default action of the submit by using either
event.preventDefault();
orreturn false
. Here is how to do the is withpreventDefault()
: