submit form without load page

How to submit a form without loading a page

If you want to submit a form without reloading the page, you will need to use JavaScript. There are several ways to do this:

1. Using AJAX

AJAX is a technique that allows you to send and retrieve data from a server without reloading the page. To use AJAX to submit a form, you will need to:

  • Create an XMLHttpRequest object
  • Open a connection to the server
  • Send the form data using the POST method
  • Handle the response from the server

Here is an example code:

// Get the form element
var form = document.getElementById("myForm");

// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Open a connection to the server
xhr.open("POST", "submit.php");

// Set the Content-Type header
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

// Send the form data
xhr.send(new FormData(form));

// Handle the response from the server
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  }
};

2. Using jQuery

If you are using jQuery, you can use the $.ajax() method to submit a form without reloading the page. Here is an example code:

// Get the form element
var form = $("#myForm");

// Submit the form using AJAX
$.ajax({
  type: "POST",
  url: "submit.php",
  data: form.serialize(),
  success: function(response) {
    console.log(response);
  }
});

3. Using Fetch API

You can also use the Fetch API to submit a form without reloading the page. Here is an example code:

// Get the form element
var form = document.getElementById("myForm");

// Send the form data using Fetch API
fetch("submit.php", {
  method: "POST",
  body: new FormData(form)
}).then(function(response) {
  return response.text();
}).then(function(data) {
  console.log(data);
});

These are some of the ways to submit a form without reloading the page. Choose the one that works best for you.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe