title: Keep input field values when form fails
body: <p>I have a pretty basic form that uses php to send an email and do some basic validation. It's also using ajax so the page doesn't have to reload on submission. The form's been working well, but if someone submits the form and it fails validation, all form fields are reset.</p>
  
  <p>How would I go about keeping the values a user has entered when the form fails? I have a feeling it'll have something to do with my javascript file, but I'm a newb with javascript and not really sure what direction to go. Can anyone help?</p>
  
  <p>Here's my form.html:</p>
  
  <pre><code>&lt;div id="response"&gt;&lt;/div&gt;
  &lt;div class="form-group"&gt;
      &lt;label for="name"&gt;Your Name:&lt;/label&gt;
    &lt;input type="text" name="name" id="name" class="form-control" placeholder="Jesse James"&gt;
  &lt;/div&gt;
  &lt;div class="form-group"&gt;
      &lt;label for="email"&gt;Email:&lt;/label&gt;
    &lt;input type="email" name="email" id="email" class="form-control" placeholder="howCan@weReachYou.com"&gt;
  &lt;/div&gt;
  &lt;div class="form-group"&gt;
      &lt;label for="phone"&gt;Phone:&lt;/label&gt;
    &lt;input type="tel" name="phone" id="phone" class="form-control" placeholder="734-968-4509"&gt;
  &lt;/div&gt;
  &lt;div class="form-group"&gt;
      &lt;label for="message"&gt;Message&lt;/label&gt;
      &lt;textarea class="form-control" id="message" name="message" rows="6" placeholder="How can we help...?"&gt;&lt;/textarea&gt;
  &lt;/div&gt;
  &lt;button type="submit" name="submit" id="submit" class="btn btn-default"&gt;Send It&lt;/button&gt;
  &lt;input type="hidden" name="honeypot" id="honeypot" value="http://"&gt;            
  &lt;input type="hidden" name="humancheck" id="humanCheck" class="clear" value=""&gt;
  </code></pre>
  
  <p></p>
  
  
  
  <p>and the ajax_sumit.js:</p>
  
  <pre><code>$(document).ready(function() {
  
      $('#contact input:submit').click(function() {
          $('#contact form').attr('action', 'http://' + document.domain + '/php/feedback.php');
          $('#contact form').submit();
      });
  
      $('form #response').hide();
      $('form #nameResponse').hide();
      $('form #phoneResponse').hide();
      $('form #emailResponse').hide();
      $('form #messageResponse').hide();
      $('#submit').click(function(e) {
  
          // prevent forms default action until
          // error check has been performed
          e.preventDefault();
  
          // grab form field values
          var valid = '';
          var nameResponse = '';
          var phoneReponse = '';
          var emailResponse = '';
          var messageResponse = '';
          var required = ' is required.';
          var name = $('form #name').val();
          var phone = $('form #phone').val();
          var email = $('form #email').val();
          var message = $('form #message').val();
          var honeypot = $('form #honeypot').val();
          var humanCheck = $('form #humanCheck').val();
  
          // perform error checking
          if (name = '' || name.length &lt;= 2) {
  
              nameResponse = '&lt;p&gt;Your name' + required +'&lt;/p&gt;';   
  
          }
  
          if (phone ) {
  
          }
  
          if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
  
              emailResponse += '&lt;p&gt;Your email' + required +'&lt;/p&gt;';                                                  
  
          }
  
          if (message = '' || message.length &lt;= 5) {
  
              messageResponse += '&lt;p&gt;A message' + required + '&lt;/p&gt;';  
  
          }   
  
          if (honeypot != 'http://') {
  
              valid += '&lt;p&gt;Spambots are not allowed.&lt;/p&gt;';    
  
          }
  
          if (humanCheck != '') {
  
              valid += '&lt;p&gt;A human user' + required + '&lt;/p&gt;'; 
  
          }
  
      // let the user know if there are erros with the form
  
          if (valid != '') {
  
  
              $('form #response').removeClass().addClass('error')
                  .html('&lt;div class="alert alert-danger"&gt;'+
                      '&lt;strong&gt;Please correct the errors below.&lt;/strong&gt;' + '&lt;/div&gt;'
                              ).fadeIn('fast');
  
              if (nameResponse != '') {
                      $('form #nameResponse').removeClass().addClass('error')
                          .html('&lt;div class="alert alert-danger"&gt;'+
                              nameResponse + '&lt;/div&gt;'
                                  ).fadeIn('fast');
              }
  
              if (phoneResponse != '') {
                      $('form #nameResponse').removeClass().addClass('error')
                          .html('&lt;div class="alert alert-danger"&gt;'+
                              phoneResponse + '&lt;/div&gt;'
                                  ).fadeIn('fast');
              }
  
              if (emailResponse != '') {
                      $('form #nameResponse').removeClass().addClass('error')
                          .html('&lt;div class="alert alert-danger"&gt;'+
                              emailResponse + '&lt;/div&gt;'
                                  ).fadeIn('fast');
              }
  
              if (messageResponse != '') {
                      $('form #nameResponse').removeClass().addClass('error')
                          .html('&lt;div class="alert alert-danger"&gt;'+
                              messageResponse + '&lt;/div&gt;'
                                  ).fadeIn('fast');
              }
  
          }
          // let the user know something is happening behind the scenes
          // serialize the form data and send to our ajax function
          else {
  
              $('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');                                      
  
              var formData = $('form').serialize();
  
              submitForm(formData);           
  
          }
  
      });
  
  });
  
  function submitForm(formData) {
      $.ajax({
  
          type:           'POST',
          url:            'php/feedback.php',
          data:           formData,
          dataType:   'json',
          cache:      false,
          timeout:    7000,
          success:    
          function(data) {
              //we are getting data.error (from ajax, which is formData) and data.msg from our feedback.php
              $('form #response').removeClass().addClass((data.error === true) ? 'error':'success')
                                          .html(data.msg).fadeIn('fast');
              if ($('form #response').hasClass('success')) {
                  setTimeout ("$('form #response').fadeOut('fast')",5000);
              }
          },
          error: 
          function (XMLHttpRequest, textStatus, errorThrown) {
              $('form #response').removeClass().addClass('error')
                          .html('&lt;div class="alert alert-danger"&gt;' +
                              '&lt;p&gt;There was an &lt;strong&gt;' + errorThrown + 
                                      '&lt;/strong&gt; error due to a &lt;strong&gt;' + textStatus +
                                          '&lt;/strong&gt; condition.&lt;/p&gt;' +
                                              '&lt;/div&gt;').fadeIn('fast');
          },
          complete: function(XMLHttpRequest, status) {
              $('form') [0].reset();
          }
  
  
  
      });
  };
  </code></pre>
  
  <p>And the feedback.php:</p>
  
  <pre><code>&lt;?php 
  sleep(.5);
  //Sanitize incoming data and store in variable
  $name = trim(stripslashes(htmlspecialchars($_POST['name'])));           
  $email = trim(stripslashes(htmlspecialchars($_POST['email'])));
  $phone = trim(stripslashes(htmlspecialchars($_POST['phone'])));
  $phoneLink = preg_replace('/\D+/', '', $phone);
  $message = trim(stripslashes(htmlspecialchars($_POST['message'])));     
  $humancheck = $_POST['humancheck'];
  $honeypot = $_POST['honeypot'];
  
  if ($honeypot == 'http://' &amp;&amp; empty($humancheck)) { 
  
          //Validate data and return success or error message
          $error_message = '';    
          $reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";
  
          if (!preg_match($reg_exp, $email)) {
  
                      $error_message .= "&lt;p&gt;A valid email address is required.&lt;/p&gt;";             
          }
          if (empty($name)) {
  
                      $error_message .= "&lt;p&gt;Please provide your name.&lt;/p&gt;";              
          }           
          if (empty($message)) {
  
                      $error_message .= "&lt;p&gt;A message is required.&lt;/p&gt;";
          }       
          if (!empty($error_message)) {
                      $return['error'] = true;
                      $return['msg'] = '&lt;div class="alert alert-danger"&gt;'."&lt;h3&gt;Oops! The request was successful but your form is not filled out correctly.&lt;/h3&gt;".$error_message;                  
                      echo json_encode($return);
                      exit();
          } 
  
          else {
              //mail variables
              #$to =              'Mainstwebguy@gmail.com';
              $to =           'Jason@mainstreetcomp.com';
              $from = $_POST['email'];
              $headers =  'From: '.$from."\r\n";
              $headers .= 'MIME-Version: 1.0' . "\r\n";
              $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
              $subject =  "Contact Form Submission\n";
  
  
              $body =         '&lt;p&gt;Name:   '.$name."&lt;/p&gt;";
              $body   .=      '&lt;p&gt;Email:  '."&lt;a href=\"mailto:".$email.'"'."&gt;".$email."&lt;/a&gt;"."&lt;/p&gt;";
              if(isset ($phone) &amp;&amp; $phone != '') {
                  $body .=    '&lt;p&gt;Phone: '.'&lt;a href="tel:+1'.$phoneLink.'"'.$phone.'&gt;'.$phone."&lt;/a&gt;";
              }
  
              $body .=        '&lt;p&gt;Message:   '.$message."&lt;/p&gt;";
  
              //send email and return a message to user
              if(mail($to, $subject, $body, $headers)) {  
                  $return['error'] = false;
                  $return['msg'] = 
                      '&lt;div class="alert alert-success"&gt;'.
                          "&lt;h3&gt;Thanks for your feedback " .$name ."&lt;/h3&gt;".
                          "&lt;p&gt;We'll reply to you at ".$email." as soon as we can.&lt;/p&gt;";
  
                          echo json_encode($return);
              }
              else {
  
                  $return['error'] = true;
                  $return['msg'] = "&lt;h3&gt;Oops! There was a problem sending the email. Please try again.&lt;/h3&gt;"; 
                  echo json_encode($return);
              }
  
          }
  
  } 
  else {
  
      $return['error'] = true;
      $return['msg'] = "&lt;h3&gt;Oops! There was a problem with your submission. Please try again.&lt;/h3&gt;";  
      echo json_encode($return);
  }
  
  ?&gt; 
  </code></pre>
  
  <p>I really appreciate any help! :-)</p>