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(document.getElementById("FORM"));
    • var xhr = new XMLHttpRequest();
    • xhr.open("POST", "SERVER-SCRIPT");
    • xhr.send(data); 
  2. Submit the form using Fetch API.
    • var data = new FormData(document.getElementById("FORM"));
    • 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.

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

  • Please use http:// for testing, not file://.
If you spot a bug, feel free to comment below. I try to answer short 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.

 

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.

 

 

FORM SUBMISSION WITHOUT RELOAD

All right, let us now get into the examples of how to submit forms without reloading the page.

 

PRELUDE) THE HTML FORM

<form onsubmit="return FUNCTION()">
  Name: <input type="text" name="name" required>
  Email: <input type="email" name="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

1A) AJAX POST SUBMISSION

1a-ajax-post.html
<script>
function ajaxpost () {
  // (A) GET FORM DATA
  var data = new FormData(document.getElementById("myForm"));
 
  // (B) AJAX
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "0-dummy.php");
  xhr.onload = function () {
    // do something when server responds
    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).

 

 

1B) AJAX GET SUBMISSION

1b-ajax-get.html
<script>
function ajaxget () {
  // (A) GET FORM DATA
  var form = new FormData(document.getElementById("myForm"));
  var data = new URLSearchParams(form).toString();
 
  // (B) AJAX
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "0-dummy.php?" + data);
  xhr.onload = function () {
    // do something when server responds
    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

2A) FETCH POST SUBMISSION

2a-fetch-post.js
<script>
function fetchpost () {
  // (A) GET FORM DATA
  var data = new FormData(document.getElementById("myForm"));
 
  // (B) FETCH
  fetch("0-dummy.php", { method: "post", body: data })
  .then(res => res.text())
  .then(txt => {
    // do something when server responds
    console.log(txt);
  })
  .catch(err => console.log(err));
 
  // (C) PREVENT HTML FORM SUBMIT
  return false;
}
</script>

Before some of you get a panic attack on what those then and catch means, here’s a quick crash course on defining functions in Javascript:

  • You already know this one – function myfunc (a, b) { return a + b; }
  • We can also do it this way – var myfunc = function (a, b) { return a + b; }
  • We can shorten that to an “arrow function” – var myfunc = (a, b) => { return a + b; }

This may throw some of you guys off for a bit, but () => {} is just the “shorthand” for defining a function. Try to follow along the sequence:

  1. The same old “get data from the HTML form”.
  2. fetch() is pretty much the “modern version” of XMLHttpRequest(), we use it to send data to the server.
    • .then((res) => { return res.text(); }) will return the server response as plain text (string).
    • .then((txt) => { console.log(txt); }) will output the server response in the console… Same as xhr.onload, this is a good place to show your “successful” or “failed” message.
    • .catch((err) => { console.log(err); } is triggered if an error occurs.
  3. return false to stop the HTML form from reloading the page.

 

 

2B) FETCH GET SUBMISSION

2b-fetch-get.js
<script>
function fetchget () {
  // (A) GET FORM DATA
  var form = new FormData(document.getElementById("myForm"));
  var data = new URLSearchParams(form).toString();
 
  // (B) FETCH
  fetch("0-dummy.php?" + data, { method: "get" })
  .then(res => res.text())
  .then(txt => {
    // do something when server responds
    console.log(txt);
  })
  .catch(err => console.log(err));
 
  // (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.

 

 

EXTRA 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
// xhr.onload = function () { console.log(this.response); };
// .then((txt) => { console.log(txt); })

 

YOUTUBE TUTORIAL

 

REFERENCES & LINKS

 

INFOGRAPHIC CHEAT SHEET

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

 

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 *