0

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.

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?

Here's my form.html:

<div id="response"></div>
<div class="form-group">
    <label for="name">Your Name:</label>
  <input type="text" name="name" id="name" class="form-control" placeholder="Jesse James">
</div>
<div class="form-group">
    <label for="email">Email:</label>
  <input type="email" name="email" id="email" class="form-control" placeholder="howCan@weReachYou.com">
</div>
<div class="form-group">
    <label for="phone">Phone:</label>
  <input type="tel" name="phone" id="phone" class="form-control" placeholder="734-968-4509">
</div>
<div class="form-group">
    <label for="message">Message</label>
    <textarea class="form-control" id="message" name="message" rows="6" placeholder="How can we help...?"></textarea>
</div>
<button type="submit" name="submit" id="submit" class="btn btn-default">Send It</button>
<input type="hidden" name="honeypot" id="honeypot" value="http://">            
<input type="hidden" name="humancheck" id="humanCheck" class="clear" value="">

and the ajax_sumit.js:

$(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 <= 2) {

            nameResponse = '<p>Your name' + required +'</p>';   

        }

        if (phone ) {

        }

        if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {

            emailResponse += '<p>Your email' + required +'</p>';                                                  

        }

        if (message = '' || message.length <= 5) {

            messageResponse += '<p>A message' + required + '</p>';  

        }   

        if (honeypot != 'http://') {

            valid += '<p>Spambots are not allowed.</p>';    

        }

        if (humanCheck != '') {

            valid += '<p>A human user' + required + '</p>'; 

        }

    // let the user know if there are erros with the form

        if (valid != '') {


            $('form #response').removeClass().addClass('error')
                .html('<div class="alert alert-danger">'+
                    '<strong>Please correct the errors below.</strong>' + '</div>'
                            ).fadeIn('fast');

            if (nameResponse != '') {
                    $('form #nameResponse').removeClass().addClass('error')
                        .html('<div class="alert alert-danger">'+
                            nameResponse + '</div>'
                                ).fadeIn('fast');
            }

            if (phoneResponse != '') {
                    $('form #nameResponse').removeClass().addClass('error')
                        .html('<div class="alert alert-danger">'+
                            phoneResponse + '</div>'
                                ).fadeIn('fast');
            }

            if (emailResponse != '') {
                    $('form #nameResponse').removeClass().addClass('error')
                        .html('<div class="alert alert-danger">'+
                            emailResponse + '</div>'
                                ).fadeIn('fast');
            }

            if (messageResponse != '') {
                    $('form #nameResponse').removeClass().addClass('error')
                        .html('<div class="alert alert-danger">'+
                            messageResponse + '</div>'
                                ).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('<div class="alert alert-danger">' +
                            '<p>There was an <strong>' + errorThrown + 
                                    '</strong> error due to a <strong>' + textStatus +
                                        '</strong> condition.</p>' +
                                            '</div>').fadeIn('fast');
        },
        complete: function(XMLHttpRequest, status) {
            $('form') [0].reset();
        }



    });
};

And the feedback.php:

<?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://' && 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 .= "<p>A valid email address is required.</p>";             
        }
        if (empty($name)) {

                    $error_message .= "<p>Please provide your name.</p>";              
        }           
        if (empty($message)) {

                    $error_message .= "<p>A message is required.</p>";
        }       
        if (!empty($error_message)) {
                    $return['error'] = true;
                    $return['msg'] = '<div class="alert alert-danger">'."<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$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 =         '<p>Name:   '.$name."</p>";
            $body   .=      '<p>Email:  '."<a href=\"mailto:".$email.'"'.">".$email."</a>"."</p>";
            if(isset ($phone) && $phone != '') {
                $body .=    '<p>Phone: '.'<a href="tel:+1'.$phoneLink.'"'.$phone.'>'.$phone."</a>";
            }

            $body .=        '<p>Message:   '.$message."</p>";

            //send email and return a message to user
            if(mail($to, $subject, $body, $headers)) {  
                $return['error'] = false;
                $return['msg'] = 
                    '<div class="alert alert-success">'.
                        "<h3>Thanks for your feedback " .$name ."</h3>".
                        "<p>We'll reply to you at ".$email." as soon as we can.</p>";

                        echo json_encode($return);
            }
            else {

                $return['error'] = true;
                $return['msg'] = "<h3>Oops! There was a problem sending the email. Please try again.</h3>"; 
                echo json_encode($return);
            }

        }

} 
else {

    $return['error'] = true;
    $return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";  
    echo json_encode($return);
}

?> 

I really appreciate any help! :-)

MainStWebGuy
  • 31
  • 2
  • 6
  • It looks to me that your form is submitting it no matter if it fails the validation or not... Because when you click submit you are preventing the default action of submitting the page and clearing the form. To test this theory comment out your form reset code in the submit form... I would also delete this code... $('#contact input:submit').click(function() { $('#contact form').attr('action', 'http://' + document.domain + '/php/feedback.php'); $('#contact form').submit(); }); It is probably causing issues. Due to it is kinda like the $("#submit").click() code. – Martin E. Aug 07 '15 at 14:44

1 Answers1

0

I think the easiest way is to store the values in a session and destroy that after processing.

this resource might help: Storing Form Data as a Session Variable

Community
  • 1
  • 1
Olli
  • 171
  • 6