Jquery ajaxSubmit not working
我尝试使用Ajax和jQuery来处理表单,淡出表单,然后淡入并显示一条成功或错误消息。不幸的是,由于某种原因,表单仍然正常提交,而不是使用Ajax。我正在使用jquery验证插件来验证表单。这是密码。
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <form name="contact" id="contact" method="post"> <label for="name" class="control-label">Your Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter your name"> <label for="email" class="control-label">Email Address:</label> <input type="email" class="form-control" id="email" name="email" placeholder="Enter your email"> <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> <button type="submit" name="submit" class="btn button btn-default">Submit</button> </form> <span> <p> Your message was sent succssfully! I will be in touch as soon as I can. </p> </span> <span> <p> Something went wrong, try refreshing and submitting the form again. </p> </span> |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | $(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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?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: "; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s ",$b,$_REQUEST[$a]); } $send = mail($to, $subject, $body, $headers); ?> |
您需要使用
1 2 | submitHandler: function(form, event) { event.preventDefault(); |
alert('something');
.
.
.
});
例如,如果未显示警报,则表示该部分未执行,您可能希望尝试其他方法。