Categories
JavaScript Answers

How to submit an HTML form without redirection with JavaScript?

Spread the love

To submit an HTML form without redirection using JavaScript, you can prevent the default form submission behavior by capturing the form submission event and then handle the form submission using JavaScript.

For example, we write:

HTML:

<form id="myForm">
  <label for="inputField">Input:</label>
  <input type="text" id="inputField" name="inputField">
  <button type="button" id="submitButton">Submit</button>
</form>

JavaScript:

// Get reference to the form and the submit button
var form = document.getElementById('myForm');
var submitButton = document.getElementById('submitButton');

// Add event listener for button click
submitButton.addEventListener('click', function() {
  // Serialize form data
  var formData = new FormData(form);

  // Example: log form data to console
  for (var pair of formData.entries()) {
    console.log(pair[0] + ': ' + pair[1]);
  }

  // Send form data using AJAX
  // Example:
  // var xhr = new XMLHttpRequest();
  // xhr.open('POST', 'your_server_url_here');
  // xhr.send(formData);

  // Prevent default form submission behavior
  return false;
});

In this example, we’ve added a button (<button type="button" id="submitButton">Submit</button>) inside the form instead of using <input type="submit">.

This button does not trigger the default form submission behavior.

Instead, when the button is clicked, the event listener attached to it captures the click event.

Inside this event listener, you can handle the form data as needed.

In the example, we serialize the form data using FormData, log it to the console for demonstration purposes, and prevent the default form submission behavior using return false;.

You can then perform further actions such as sending the form data via AJAX to a server for processing.

Adjust the JavaScript code inside the event listener to handle the form submission according to your specific requirements.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *