2016-06-28 114 views
0

我有一个表单,如果电子邮件是错误的给我一个错误信息,而我留在同一页上,这是可能的,因为我用阿贾克斯。现在我试图实现当我提交表单和返回是表单重置的错误。重置表单后提交

我试过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 = "[email protected]"; 
    $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; 
}); 
+0

你看了PHP手册,复位功能是什么? *将数组的内部指针设置为其第一个元素*无论如何,我认为您希望在表单submit上添加一个'event.preventDefault();'并将事件作为参数添加到该js函数中。 – vaso123

+1

如果您想要删除POST电子邮件变量,请使用'unset($ _ POST ['subscribefield'])'代替。如果你想重置表单值:尝试'$('。form.subscribe')[0] .reset();' –

+0

@NachoM。没有工作; _; –

回答

1

如果你真的想要做的是空表单值尝试:

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

将这个按钮,你<form>内:

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

,使该按钮时,你在这样的回报找到错误点击,

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

我的提交按钮 –

+0

会发生什么情况无需更改提交按钮 –

0

我做就像ajax调用成功了,但出错了,然后重置客户端上的表单。

例如:

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

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