我正在尝试使用ajax和jQuery来处理表单,淡出表单然后淡入成功或错误消息。不幸的是,由于某种原因,表单仍然正常提交而不是使用ajax。我正在使用jQuery验证插件来验证表单。这是代码。
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 = "youremail@domain.com";
$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);
?>
答案 0 :(得分:3)
您需要使用event.preventDefault();
或return false
停止提交的默认操作。以下是preventDefault()
:
submitHandler: function(form, event) {
event.preventDefault();
答案 1 :(得分:0)
$(form).ajaxSubmit({
alert('something');
.
.
.
});
例如,如果未显示警报,则表示该部分未执行,您可能想尝试不同的方式。