MOHAMMED MOHAMMED - 6 months ago 10
Ajax Question

clear form values submitting through ajax

Here my form is getting cleared through ajax and i had validation for all the fields and the problem am facing here is when i enter data for one field and submitting the form the value entered in that field is getting disappeared i want that to be remain.
Here is my ajax please have a look

<script type="text/javascript">
$('#send').click(function() {

var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()

};
$.ajax({
url: "<?php echo base_url();?>roxcontrol/contact_form",
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 'YES')
$('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
else if (msg == 'NO')
$('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');

}


});


$( '#contact' ).each(function(){
this.reset();
});


return false;


});

</script>

Answer

Use trigger to reset your form after success event. You are resetting form outside of ajax so on every call it will reset. Try below code

 <script type="text/javascript">
 $('#send').click(function() {

var form_data = {
  name: $('#name').val(),
  email: $('#email').val(),
  message: $('#message').val()

};
$.ajax({
  url: "<?php echo base_url();?>roxcontrol/contact_form",
  type: 'POST',
  data: form_data,
  success: function(msg) {
    if (msg == 'YES')
    {
      $('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
        $( '#contact' ).trigger("reset");
     }
    else if (msg == 'NO')
      $('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
    else
      $('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');

  }


});


return false;


});

</script>
Comments