Submit form without page refresh using Jquery not working

Viewed 35

I'm trying to submit a form but it doesn't work. It will just refresh the page and then do nothing.

<form method="post" accept-charset="utf-8" id="contactform" class="pure-form">
  <input type="text" name="name" id="name" class="pure-input-1-2" placeholder="Vor- und Nachname" required>
  <input type="email" name="email" id="email" class="pure-input-1-2" placeholder="E-Mail" required>
  <textarea class="pure-input-1-2" name="message" id="message" rows="10" placeholder="Nachricht" required></textarea>
  <input type="hidden" name="ip" id="ip" value="<?php echo $_SERVER[" REMOTE_ADDR "]; ?>">
  <input type="hidden" name="date" id="date" value="<?php echo date(" Y-m-d H:i:s "); ?>">
  <button type="submit" name="mysubmit" id="mysubmit" class="pure-button pure-input-1-2 pure-button-primary">Nachricht senden</button>
</form>
$('#mysubmit').submit(function(e) {
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: 'inc/xxx.php',
    data: $('#contactform').serialize(),
    dataType: "text",
    success: function(data) {

    }
  });
});
1 Answers

#mysubmit is the button, which does not have a submit event. Hence the form is being submit as a standard request.

To fix this, hook to the submit event of the form element instead:

$('#contactform').submit(function(e) {
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: 'inc/xxx.php',
    data: $(this).serialize(),
    dataType: "text",
    success: function (data) {

    }
  });
});
Related