2 Easy Ways To Submit HTML Form Without Refreshing Page

Welcome to a quick tutorial and examples on how to submit an HTML form without refreshing the page. So you have an HTML form that needs to stay on the same page after submission?

The common ways to submit an HTML form without reloading the page are:

  1. Submit the form using AJAX.
    • var data = new FormData();
    • data.append("KEY", document.getElementById("FIELD"));
    • var xhr = new XMLHttpRequest();
    • xhr.open("POST", "SERVER-SCRIPT");
    • xhr.send(data); 
  2. Submit the form using Fetch API.
    • var data = new URLSearchParams();
    • data.append("KEY", document.getElementById("FIELD"));
    • fetch(SERVER-SCRIPT", { method: 'post', body: data });

That covers the basics, but let us walk through more examples in this guide – Read on!

ⓘ I have included a zip file with all the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Form Submission Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

Please use http:// for testing, not file://. If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

FORM SUBMISSION WITHOUT RELOAD

All right, let us now get started with the examples on how to submit forms without reloading the page.

 

PRELUDE) THE HTML FORM

<form onsubmit="return FUNCTION()">
  Name: <input type="text" id="user-name" required/>
  Email: <input type="email" id="user-email" required/>
  <input type="submit" value="Go!"/>
</form>

First, this is the simple HTML form that we will be working with (for all the below examples). Nothing “special” here, just take note of the onsubmit="return FUNCTION()" part – We will be using Javascript to process the form instead.

 

METHOD 1) SUBMIT FORM USING AJAX

AJAX POST SUBMISSION

1a-ajax-post.html
<script>
function ajaxpost(){
  // (A) GET FORM DATA
  var data = new FormData();
  data.append("name", document.getElementById("user-name").value);
  data.append("email", document.getElementById("user-email").value);
 
  // (B) AJAX
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "0-dummy.php");
  // What to do when server responds
  xhr.onload = function(){ console.log(this.response); };
  xhr.send(data);
 
  // (C) PREVENT HTML FORM SUBMIT
  return false;
}
</script>

AJAX stands for “Asynchronous Javascript And XML”, and I will leave a link below if you want to learn more. Anyway, submitting forms with AJAX is as simple as:

  1. Create a FormData() object to collect data from the HTML form fields.
  2. Next, the AJAX request itself. Take extra note of the xhr.onload section, this is what to do upon completion (when the server responds) – A good place to show a “successful” message or follow up with the next step. Use this.response to fetch the server response and this.status for the HTTP status code.
  3. Finally, remember to return false. This will prevent the default HTML form submission (and not reload the entire page).

 

 

AJAX GET SUBMISSION

1b-ajax-get.html
<script>
function ajaxget(){
  // (A) GET FORM DATA
  var data = new URLSearchParams();
  data.append("name", document.getElementById("user-name").value);
  data.append("email", document.getElementById("user-email").value);
 
  // (B) AJAX
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "0-dummy.php?" + data.toString());
  // What to do when server responds
  xhr.onload = function(){ console.log(this.response); };
  xhr.send();
 
  // (C) PREVENT HTML FORM SUBMIT
  return false;
}
</script>

If you want to do a GET submission with AJAX – It is pretty much the same process. The only difference here is that the data is appended to the URL as a query string.

 

METHOD 2) SUBMIT FORM USING FETCH

FETCH POST SUBMISSION

2a-fetch-post.js
<script>
function fetchpost(){
  // (A) GET FORM DATA
  let data = new URLSearchParams();
  data.append("name", document.getElementById("user-name").value);
  data.append("email", document.getElementById("user-email").value);
 
  // (B) FETCH
  fetch("0-dummy.php", {
    method: 'post',
    body: data
  })
  .then(function (response) {
    return response.text();
  })
  .then(function (text) {
    console.log(text);
  })
  .catch(function (error) {
    console.log(error)
  });
 
  // (C) PREVENT HTML FORM SUBMIT
  return false;
}
</script>

As you can see, the process with fetch() is pretty similar to AJAX, but the usage is totally different.

  1. Same old “get data from the form fields”.
  2. The fetch() function followed by .then().catch(). This is a part of the promise mechanism and I will leave links below if you want to learn more. This may throw some beginners off, but just follow along with the sequence:
    • First, fetch() (send data) to the server script.
    • Then return response.text() when the server responds.
    • Then do something with the server response – Show the message to the user, or follow up with the next step.
    • Lastly, catch any errors if they occur.
  3. Same, return false to stop the HTML form from reloading the page.

 

 

FETCH GET SUBMISSION

2b-fetch-get.js
<script>
function fetchget(){
  // (A) GET FORM DATA
  let data = new URLSearchParams();
  data.append("name", document.getElementById("user-name").value);
  data.append("email", document.getElementById("user-email").value);
 
  // (B) FETCH
  fetch("0-dummy.php?" + data.toString(), { method: 'get' })
  .then(function (response) {
    return response.text();
  })
  .then(function (text) {
    console.log(text);
  })
  .catch(function (error) {
    console.log(error)
  });
 
  // (C) PREVENT HTML FORM SUBMIT
  return false;
}
</script>

Pretty much the same again. Just change to method: 'get' and append the form data to the URL query string instead.

 

 

USEFUL BITS & LINKS

That’s all for the code, and are a few small extras that may be useful to you.

 

EXTRA – HOW ABOUT THE SERVER-SIDE?

0-dummy.php
<?php
// (A) DO YOU PROCESSING AS USUAL - IN ANY LANGUAGE
$foo = 123;
$foo += 456;
$pass = $foo < 123456;
 
// (B) OUTPUT A MESSAGE AT THE END
echo $pass ? "OK" : "ERROR MESSAGE" ;
 
// THIS MESSAGE WILL BE PICKED UP IN AJAX OR FETCH
// AJAX -> XHR.ONLOAD -> THIS.RESPONSE
// FETCH -> THEN...RETURN RESPONSE.TEXT() -> THEN...TEXT

 

YOUTUBE TUTORIAL

 

INFOGRAPHIC CHEAT SHEET

How To Submit HTML Form Without Reloading Page (click to enlarge)

 

REFERENCES & LINKS

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

3 thoughts on “2 Easy Ways To Submit HTML Form Without Refreshing Page”

  1. Very clear and useful tutorial.
    I would like to use the 1st method (AJAX form submit) to post data to a specific endpoint that returns a JSON object response. I need to assign this response (just an item, actually) to a variable that I want to use in a template literals. Is it possible? What would you suggest? Thanks in advance.

Leave a Comment

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