表单字段未被Ajax清除

时间:2014-07-04 12:37:54

标签: javascript php jquery ajax forms

好的我按照教程创建了一个ajax表单。一切都很好。但是我的表单字段在提交后没有清除。我在这里搜索过&找到了一些解决方案,但不适合我。我试过了:

number 1: $('form#contactform input[type="text"],texatrea, select').val('');

number 2: $("#name").val("");
$("#email").val("");
$("#phone").val("");

number 3:  $('#contactform')[0].reset();

但是这个解决方案对我不起作用。

我的HTML:

    <div id="form-messages"></div>
    <form method="post" action="mailer.php" name="contactform" id="contactform">
        <fieldset>


                <div class="col-sm-3 col-xs-6">
                <!-- Name -->
                <input name="name" type="text" id="name" size="30" placeholder="Name" value="" />
                </div>


                <div class="col-sm-3 col-xs-6">
                <!-- Email -->
                <input name="email" type="text" id="email" size="30" placeholder="Email" value="" />
                </div>


                <div class="col-sm-3 col-xs-6">
                <!-- Phone -->
                <input name="phone" type="text" id="phone" size="30" placeholder="Phone" value="" />
                </div>


                <div class="col-sm-3 col-xs-12">
                <!-- Send button -->
                <input type="submit" class="submit" id="submit" value="Send message" />
                </div>


        </fieldset>
    </form>

我的js:

$(function() {

    // Get the form.
    var form = $('#contactform');

    // Get the messages div.
    var formMessages = $('#form-messages');

    // Set up an event listener for the contact form.
    $(form).submit(function(e) {
        // Stop the browser from submitting the form.
        e.preventDefault();

        // Serialize the form data.
        var formData = $(form).serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // Clear the form.
            $('form#contactform input[type="text"],texatrea, select').val('');

            // Set the message text.
            $(formMessages).text(response);


        })
        .fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });

    });

});

&安培;我的Php

<?php

    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
                $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $phone = strip_tags(trim($_POST["phone"]));
                $phone = str_replace(array("\r","\n"),array(" "," "),$phone);

        // Check that data was sent to the mailer.
        if ( empty($name) OR empty($phone) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        // FIXME: Update this to your desired email address.
        $recipient = "friday@imransdesign.com";

        // Set the email subject.
        $subject = "New contact from $name";

        // Build the email content.
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n";
        $email_content .= "Phone: $phone\n";

        // Build the email headers.
        $email_headers = "From: $name <$email>";

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            header("HTTP/1.0 404 Not Found");
            echo "Thank You! Your message has been sent.";
            $_POST=array();
        } else {            
            // Set a 500 (internal server error) response code.
            header("HTTP/1.0 404 Not Found");
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        header("HTTP/1.0 404 Not Found");
        echo "There was a problem with your submission, please try again.";
    }

?>

我该怎么办? 实例:http://imransdesign.com/ajax-form/

4 个答案:

答案 0 :(得分:3)

您的数字1选择器错误。它应该是:

$('#contactform').find('input[type="text"], texatrea, select').val('');

我不知道2号和3号。可能你的页面中有重复的ID ...让我来看看。 您的ID很好。还有其他事情需要继续。

我在页面上的开发工具控制台中测试了第二和第三,它们运行良好:

$('#contactform')[0].reset(); //cleared the whole form

$('#name').val(''); // Cleared the name field.

您的服务器似乎有问题。它返回 400/404 ---失败,因为您没有在.fail回调中清除您的表单,您的表单将不会被清除。未调用.done回调:

mailer.php  POST 400 text/html jquery-2.1.0.min.js:4 279 B 378 ms   
mailer.php  POST 400 text/html jquery-2.1.0.min.js:4 279 B 339 ms   
mailer.php  POST 404 text/html jquery-2.1.0.min.js:4 256 B 343 ms   

服务器以某种方式返回Thank You! Your message has been sent.,由.fail()中的以下部分输出:

if (data.responseText !== '') {
   $(formMessages).text(data.responseText);
} else {

答案 1 :(得分:0)

这样做:

.done(function(response) { 
    ...
    contactform.reset();
}

答案 2 :(得分:0)

我认为您需要清除表单标签内的所有输入字段

$("#formid").find('input, textarea').not(":submit").val('');

FIDDLE将清除提交时表单标记内的所有输入字段和textarea ..根据需要更改它..仅举例

答案 3 :(得分:0)

尝试

$('#contactform fieldset div input').val('');

而不是

$('form#contactform input[type="text"],texatrea, select').val('');