Skip to content
the poor coder

submit form without load page

Poor Man
Published
Reading time
2 min read
On this 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:

Text
// 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:

Text
// 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:

Text
// 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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC