borrepol
borrepol

Reputation: 23

Redirect after submitting a form (HTML, PHP)

I have made a test which is divided over a couple of pages. Then when people click the submit button, I want to redirect them, after saving, to the next page. For some reason, a submit button submits and then immediately refreshes the page. So the javascript for redirecting is not even run.

HTML:

<form method="post" action="" id="formwrap">
  <!-- questions here -->
  <input id="submitButton" class="block" type = "submit" name = "verzenden" value = "Opslaan" onClick="nextPage();"/>
</form>

And the JavaScript:

function nextPage() {
  window.location.href = "test.php";
}

Any ideas? I've already tried: making the input type="button" and then making a javascript submit function; in the <form> tag onSubmit="nextPage()"; Things with preventDefault, to prevent the submit button from reloading the page.

I get the feeling that it's a MUST for a submit button to reload or something. So maybe there is a way to redirect AFTER reloading the page. Well, I have no idea. Any help would be more than welcome!

Upvotes: 2

Views: 17015

Answers (1)

Seth
Seth

Reputation: 10454

First, remove the inline handler on your submit button. Your HTML should look like so:

<form method="post" action="" id="formwrap">
  <!-- questions here -->
  <input id="submitButton" class="block" type="submit" name="verzenden" value="Opslaan" />
</form>

Then, update your JavaScript to add an event handler that targets your formwrap element's submit event. Then prevent the form from making a post-back with preventDefault. Once the default behavior is prevented, you can send the user to whatever url you want :)

document
  .getElementById("formwrap")
  .addEventListener("submit", function(e) {
    e.preventDefault();
    window.location.href = "test.php";
  });

Upvotes: 6

Related Questions