Reputation: 406
I have a form which if the email is wrong gives me an error message while i stay on the same page, this is possible because i used ajax. Now I'm trying to achieve when i submit the form and the return is an error that the forms reset.
I tried reset();
but it didn't work.
<?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";
?>
and
$('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;
});
Upvotes: 0
Views: 2368
Reputation: 682
If what you really want to do is to empty the form values try:
$(':input','form.subscribe')
.not(':button, :submit, :reset, :hidden')
.val('') .removeAttr('checked')
.removeAttr('selected');
Upvotes: 1
Reputation: 354
I do something like if the ajax call was success, but something went wrong, then reset the form on the client side.
For example:
success: function(resp) {
// if the form is invalid
if (resp.invalid) {
// find your elems
$('#myForm').find('input[type=text]').val("");
}
}
On the other hand you should validate the form firstly on the client side then on the server too. For example this library can be very useful.
Upvotes: 0
Reputation: 1257
Put this button inside your <form>
:
<input type="reset" value="Reset Form" id="resetButton" >
and make a click on this button whenever you find error in return like this,
$("#resetButton").click();
Upvotes: 0