How to redirect to another page after submitting a form?

Member

by kadin , in category: Third Party Scripts , 19 days ago

How to redirect to another page after submitting a form?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 18 days ago

@kadin 

To redirect to another page after submitting a form, you can include a redirect URL in the form action attribute. Here is an example using HTML:

1
2
3
4
<form action="redirectPage.html" method="POST">
  <!-- form fields -->
  <input type="submit" value="Submit">
</form>


In this example, when the form is submitted, the browser will redirect to redirectPage.html. You can also use JavaScript to redirect to another page after form submission. Here is an example using JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
document.querySelector('form').addEventListener('submit', function(event) {
  event.preventDefault(); // prevent the form from submitting normally

  // get form data
  const formData = new FormData(this);

  // make an AJAX request to submit the form data
  // after successful submission, redirect to another page
  fetch('submitForm.php', {
    method: 'POST',
    body: formData
  })
  .then(function(response) {
    if (response.ok) {
      // redirect to another page
      window.location.href = 'redirectPage.html';
    } else {
      // handle error
      console.error('Form submission failed');
    }
  })
  .catch(function(error) {
    console.error('Error:', error);
  });
});


In this example, when the form is submitted, the form data is submitted via AJAX and then a redirect to redirectPage.html is triggered after successful submission.