Elyor
Elyor

Reputation: 5532

reset form on submit button

when user submits the form ajax will validate the form and page will not be reloaded. now it is keeping the details user entered.

How can I reset the form once user submitted the form?

<form id="contact-form" method="post">
<input name="name" type="text"/>
<button type="submit">Submit</button>
</form>

here is my ajax

$('#contact-form').on('submit',function(e) {  
$.ajax({
  url:'contact.php', 
  data:$(this).serialize(),
  type:'POST',
  success:function(data){
    console.log(data);
    swal("Thank you", "Message is sent :)", "success");
  },
  error:function(data){
    swal("Sorry", "Failed to send. Please try later :(", "error");
  }
});
e.preventDefault(); 
});

Upvotes: 0

Views: 810

Answers (2)

rybo111
rybo111

Reputation: 12588

jQuery.ajax() now uses done() and fail() and success() is deprecated as of jQuery 1.8.

$(document).on('submit', '#contact-form', function(e){
  $.ajax({
    url: 'contact.php',
    method: 'POST',
    data:$(this).serialize()
  })
    .done(function(data) {
      console.log(data);
      swal("Thank you", "Message is sent :)", "success");
      $('#contact-form')[0].reset();
    })
    .fail(function(data) {
      console.log(data);
      swal("Sorry", "Failed to send. Please try later :(", "error");
    });
  e.preventDefault();
});

Upvotes: 0

ODelibalta
ODelibalta

Reputation: 2244

Plain JavaScript

document.getElementById("contact-form").reset();

jQuery

$("form").trigger("reset"); you may need to replace form with the id of your form.

another jQuery $("#contact-form")[0].reset();

What version of Jquery do you use ? As of ver 1.8 success and error are depreciated and you should use done and fail instead.

Upvotes: 1

Related Questions