提交后重置表单

时间:2016-06-28 07:43:37

标签: php ajax forms

我有一个表格,如果电子邮件错误给我一个错误信息,而我留在同一页面,这是可能的,因为我使用ajax。现在,当我提交表单时,我试图实现,返回是表单重置的错误。

我尝试了reset();,但它没有用。

<?php
    header("Refresh:7; url=contact.php");
    $email = $_POST['subscribefield'];

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Dit emailadres klopt niet";
      reset($email);
    }


    $to = "flash1996mph@hotmail.com";
    $subject = "Abonee voor de nieuwsbrief";
    $body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";

    mail($to, $subject, $body);
    echo "U heeft zich zojuist aangemeld voor de vandenberg nieuwsbrief";
?>

$('form.subscribe').on('submit', function() {
    var that = $(this),
    url = that.attr('action'),
    method = that.attr('method'),
    data = {};

    that.find('[name]').each(function(index, value) {
        var that = $(this),
        name = that.attr('name'),
        value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type:method,
        data: data,
        success: function(response) {
            $('#success-message').html(response).show();
            setTimeout(function() {
                $('#success-message').fadeOut('slow');
            }, 2000); 
        }
    });
    return false;
});

3 个答案:

答案 0 :(得分:1)

如果您真正想要的是清空表单值,请尝试:

$(':input','form.subscribe')
 .not(':button, :submit, :reset, :hidden')
 .val('') .removeAttr('checked')
 .removeAttr('selected');

答案 1 :(得分:0)

将此按钮放在<form>

<input type="reset" value="Reset Form" id="resetButton" >

并在您发现错误时点击此按钮,

$("#resetButton").click();

答案 2 :(得分:0)

我做了类似的事情,如果ajax调用成功,但出了点问题,然后重置客户端上的表单。

例如:

success: function(resp) {
    // if the form is invalid
    if (resp.invalid) {
        // find your elems
        $('#myForm').find('input[type=text]').val("");
    }
}

另一方面,您应首先在客户端验证表单,然后在服务器上验证表单。例如,this library可能非常有用。