wayta
wayta

Reputation: 45

How can I prevent redirecting to php file after submission?

I have a problem with the submission of a form. The form data is sent to the server as it should do but after clicking on the send button I get redirected to the php file. After the submission I would like to keep being on the same page.

Here's the code:

window.addEventListener('load', function() {

  $(document).ready(function() {

    $("#send").click(function(e) {
      e.preventDefault();
      $.ajax({
        type: 'POST',
        url: 'submitmessage.php',
        data: $('form').serialize(),
        success: function() {
          console.log("Submission succeeded");
          document.getElementById("send").innerHTML = "Sent";
        },
        error: function() {
          console.log("Error");
        }
      });
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="submitmessage.php" method="POST">
  <input id="name" name="name" placeholder="Name" type="text" ></input>
  <input id="email" name="email" placeholder="email" type="email" ></input>
  <textarea id="message" name="message" maxlength="100" placeholder="Write here"></textarea><br>
  <button id="send" name="send">Submit</button>
</form>

Upvotes: 1

Views: 76

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

Instead of using a handler on a specific button, assign it to the Form:

$('form[action="submitmessage.php"]').on("submit", function(e) {

  // prevent default browser form submit 
  e.preventDefault(); 
  
  // We'll use AJAX instead:
  $.ajax({
    type: 'POST',
    url: this.action,
    data: $(this).serialize(),
    success: function() {
      $("#send").text("Sent");
    },
    error: function() {
      $("#send").text("Error");
    }
  });
});

Upvotes: 3

shaedrich
shaedrich

Reputation: 5735

The problem is the button <button id="send" name="send">Submit</button>. This is a "random" button and the e.preventDefault(); prevents nothing. If you change it to <input type="submit" id="send" name="submit" /> now actually submits the form. To prevent this, listen for $('form').submit(function(e) {}); instead.

Upvotes: 1

Related Questions