php – How to do so that the form is blank after being sent?

Question:

Hello, I have a contact form which, after sending the message successfully, remains open with the message that the client wrote and if the SEND button is clicked again, it resends it again and again. How can I correct this? What should I do so that the form is blank after it is sent and if I prevent it from being sent again? I have looked for information on how to do it with AJAX, but my knowledge of javascript is scarce and I don't know where to add a .reset(); which from what I've read in ( some other question ) similar, is how I could clean up the form. I have tried putting it in various parts of the code, but it doesn't work. I show you the code I have so that you can see the errors it has. As I said, I do not know where or what I should put exactly. I keep looking for solutions in other questions, but every time I am messing up the code without any solution. Thanks

//  -************** CODIGO PHP ************  //

<?php

/***************** Configuration *****************/

$contact_email_to = "cuentaclientdiana@gmail.com";
$contact_subject_prefix = "Mensaje de formulario de contacto: ";
$contact_error_name = "¡El nombre es demasiado corto o vacío!";
$contact_error_email = "Por favor, introduzca un email valido";
$contact_error_subject = "El tema es demasiado corto o vacío!";
$contact_error_message = "Mensaje demasiado corto! Por favor, introduzca algo.";

/********** Do not edit from the below line ***********/

if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
  die('Sorry Request must be Ajax POST');
}

if(isset($_POST)) {

  $name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
  $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
  $subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
  $message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);

  if(strlen($name)<4){
    die($contact_error_name);
  }

  if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    die($contact_error_email);
  }

  if(strlen($message)<3){
    die($contact_error_subject);
  }

  if(strlen($message)<3){
    die($contact_error_message);
  }

  if(!isset($contact_email_from)) {
    $contact_email_from = "contactform@" . @preg_replace('/^www\./','', $_SERVER['SERVER_NAME']);
  }

  $sendemail = mail($contact_email_to, $contact_subject_prefix . $subject, $message,
    "From:  $name <$contact_email_from>" . PHP_EOL .
    "Reply-To: $email" . PHP_EOL .
    "X-Mailer: PHP/" . phpversion()
  );

  if( $sendemail ) {
    echo 'OK';
  } else {
    echo 'No se pudo enviar el correo! Por favor, compruebe su configuración de correo PHP.';
  }
}
?>

////////////////////////////////////////////

// ***********  CODIGO   JAVASCRIPT ********* //


jQuery(document).ready(function($) {
"use strict";

    //Contact
    $('form.contactForm').submit(function(){

        var f = $(this).find('.form-group'), 
        ferror = false, 
        emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

        f.children('input').each(function(){ // run all inputs

            var i = $(this); // current input
            var rule = i.attr('data-rule');

            if( rule !== undefined ){
            var ierror=false; // error flag for current input
            var pos = rule.indexOf( ':', 0 );
            if( pos >= 0 ){
                var exp = rule.substr( pos+1, rule.length );
                rule = rule.substr(0, pos);
            }else{
                rule = rule.substr( pos+1, rule.length );
            }
            
            switch( rule ){
                case 'required':
                if( i.val()==='' ){ ferror=ierror=true; }
                break;
                
                case 'minlen':
                if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
                break;

                case 'email':
                if( !emailExp.test(i.val()) ){ ferror=ierror=true; }
                break;

                case 'checked':
                if( !i.attr('checked') ){ ferror=ierror=true; }
                break;
                
                case 'regexp':
                exp = new RegExp(exp);
                if( !exp.test(i.val()) ){ ferror=ierror=true; }
                break;
            }
                i.next('.validation').html( ( ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
            }
        });
        f.children('textarea').each(function(){ // run all inputs

            var i = $(this); // current input
            var rule = i.attr('data-rule');

            if( rule !== undefined ){
            var ierror=false; // error flag for current input
            var pos = rule.indexOf( ':', 0 );
            if( pos >= 0 ){
                var exp = rule.substr( pos+1, rule.length );
                rule = rule.substr(0, pos);
            }else{
                rule = rule.substr( pos+1, rule.length );
            }
            
            switch( rule ){
                case 'required':
                if( i.val()==='' ){ ferror=ierror=true; }
                break;
                
                case 'minlen':
                if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
                break;
            }
                i.next('.validation').html( ( ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
            }
        });
        if( ferror ) return false; 
        else var str = $(this).serialize();		
            $.ajax({
                type: "POST",
                url: "contactform/contactform.php",
                data: str,
                success: function(msg){
                   // alert(msg);
                    if(msg == 'OK') {
                        $("#sendmessage").addClass("show");			
                        $("#errormessage").removeClass("show");	
                    }
                    else {
                        $("#sendmessage").removeClass("show");
                        $("#errormessage").addClass("show");
                        $('#errormessage').html(msg);
                    }
                    
                }
            });
        return false;
    });

});
<!DOCTYPE html>
<html lang="en">
<body>
<section id="contact-page">
    <div class="container">
      <div class="center">
        <h2>Deje su mensaje</h2>
        <p class="lead">Deje su mensaje con sus ideas y veremos que es lo mejor para usted y su negocio.</p>
      </div>
      <div class="row contact-wrap">
        <div class="col-sm-8 col-sm-offset-2">
          <div id="sendmessage">Your message has been sent. Thank you!</div>
          <div id="errormessage"></div>
          <form action="" method="post" role="form" class="contactForm">
            <div class="form-group">
              <input type="text" name="name" class="form-control" id="name"  placeholder="Nombre" data-rule="minlen:4" data-msg="Por favor ingrese al menos 4 caracteres" />
              <div class="validation"></div>
            </div>
            <div class="form-group">
              <input type="email" class="form-control" name="email" id="email"   placeholder="Email" data-rule="email" data-msg="Por favor introduzca una dirección de correo electrónico válida" />
              <div class="validation"></div>
            </div>
            <div class="form-group">
              <input type="text" class="form-control" name="subject" id="subject"  placeholder="Tema" data-rule="minlen:4" data-msg="Por favor ingrese al menos 8 caracteres del tema" />
              <div class="validation"></div>
            </div>
            <div class="form-group">
              <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Por favor escribe algo para nosotros" placeholder="Mensaje"></textarea>
              <div class="validation"></div>
            </div>
            <input type="checkbox" name="acceptPolicies" required="required" value="acceptPolicies" /> He leído y acepto su <a href="privacidad.html" target="_blank">Política de Privacidad</a>
            <div class="text-center"><button type="submit" class="btn btn-primary btn-lg">Enviar</button></div>
          </form>
        </div>
      </div>
      <!--/.row-->
    </div>
    <!--/.container-->
  </section>
</body>
</html>

Answer:

You can put a JQuery code that cleans the fields when the ajax runs successfully. You can put a common class for all the form fields or use the 'form-control' class that I think you already use for all of them. Example $(".form-control").val("") and that's it, the value (val) will be cleaned up because you put some empty quotes.

Scroll to Top