表单失败时保留输入字段值

时间:2015-08-07 14:29:09

标签: javascript php jquery html forms

我有一个非常基本的表单,它使用php发送电子邮件并进行一些基本验证。它也使用ajax,因此页面不必在提交时重新加载。该表单运行良好,但如果有人提交表单但验证失败,则会重置所有表单字段。

如何在表单失败时保留用户输入的值?我有一种感觉它与我的javascript文件有关,但我是一个带有javascript的newb并且不确定要走哪条路。有人可以帮忙吗?

这是我的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="">

和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();
        }



    });
};

和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);
}

?> 

我非常感谢任何帮助! : - )

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是将值存储在会话中并在处理后将其销毁。

此资源可能有所帮助:Storing Form Data as a Session Variable