如何在ajax提交后清除表单?

时间:2016-10-04 13:30:39

标签: php html ajax forms

我有一个小的联系表格。发送邮件正在运行,但表单在提交后仍保留文本。我搜索并尝试了一些代码来清除它但没有成功。

// JavaScript Document
$('#contact-form').submit(function (e) {
"use strict";
e.preventDefault();
$.ajax({
    type: "POST",
    url: "contactform.php",
    data: $(this).serialize(), //get form values
    sucess: function (data) {
        document.getElementById("contact-form").reset();
    }

}).done(function (data) {
    console.log(data); // will contain success or invalid 
});
});

还有一些php

<?php
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$message = $_POST["message"];

$EmailTo = "marcin@rmonline.com";
$Subject = "New Message Received";

// prepare email body text
$email_content .= "Firstname: $firstname\n";
$email_content .= "Lastname: $lastname\n";
$email_content .= "Email: $email\n";
$email_content .= "Phone: $phone\n";
$email_content .= "Message: $message";

// send email
$success = mail($EmailTo, $Subject, $email_content, "From:".$email);

// redirect to success page
if ($success){

    echo "success";

} else {
    echo "invalid";
} 
?>

和html

<form id="contact-form" method="post" action="contactform.php" role="form">
  <div class="messages"></div>
  <div class="form-group">
    <input id="form_name" type="text" name="firstname" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
    <div class="help-block with-errors"></div>
  </div>
  <div class="form-group">
    <input id="form_lastname" type="text" name="lastname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
    <div class="help-block with-errors"></div>
  </div>
  <div class="form-group">
    <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
    <div class="help-block with-errors"></div>
  </div>
  <div class="form-group">
    <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
    <div class="help-block with-errors"></div>
  </div>
  <div class="form-group">
    <textarea id="form_message" name="message" class="form-control" placeholder="Message for us *" rows="4" required data-error="Please,leave us a message."></textarea>
    <div class="help-block with-errors"></div>
  </div>
  <button type="submit" class="btn" value="Send message">Send Message</button>
  <p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>

我感觉自己错过了什么,但还不知道是什么。

2 个答案:

答案 0 :(得分:5)

你可以使用jQuery实现它,把它放在ajax成功响应之后。

$('#contact-form')[0].reset(); 

OR

$(this).closest('form').find("input[type=text], textarea").val("");

答案 1 :(得分:-1)

尝试删除preventDefault。页面重新加载后,表单将清空。那或者您必须手动将表单输入的值设置为空。

您是否有特殊原因使用ajax提交表单而不允许表单直接发布到php文件?