Konstantin Mokhov Konstantin Mokhov - 1 month ago 8
Ajax Question

Ajax form send error

I'm have a

form
that sends data to a server. When the form is usual HTML it works fine. All data is sent to the server without error. However when I change the form to use AJAX I get an error.

<form id="form" action="handler.php" method="POST"> <!-- it's work -->
<input id="contact_name" type="text" name="name" placeholder="NAME">
<input id="contact_phone" type="text" name="phone" placeholder="PHONE">
<button type="submit">Get call</button>
</form>


$(document).ready(function() {
/*this does not work*/
$('#form').on('submit', function(e) {
var dataf = $(this).serialize();
$.ajax({
url: 'handler.php',
type: 'POST',
data: dataf,
success: function(response) {
console.log(JSON.stringify(response));
},
error: function(response) {
console.log(JSON.stringify(response));
}
});
});
});


In console I get this:

{"readyState":0,"responseText":"","status":0,"statusText":"error"}

Answer

You have to add e.preventDefault();

$(document).ready(function(){/*this does not work*/
  $('#form').on('submit', function(e) {
    e.preventDefault();
    var dataf = $(this).serialize();
      $.ajax({
        url: 'handler.php',
        type: 'POST',
        data: dataf,
        success: function(response) {
          console.log(JSON.stringify(response));
        },
        error: function(response) {
          console.log(JSON.stringify(response));
        }
      });
  });
});