maw2be maw2be - 3 years ago 325
Ajax Question

How to clear form after ajax submit?

I have a small contact form. Sending messages is working but the form stays with text after submitting. I searched and tried some code to clear it with no success.

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

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

And some php

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

$EmailTo = "";
$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";

And 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 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 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 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 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>
<button type="submit" class="btn" value="Send message">Send Message</button>
<p class="text-muted"><strong>*</strong> These fields are required.</p>

I've got the feeling that I'm missing something, but don't know what yet.

Answer Source

You can achieve it by using jQuery, put it after ajax success response.



$(this).closest('form').find("input[type=text], textarea").val("");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download