Welcome to a quick tutorial on how to submit an HTML form without reloading the page. So you want the user to stay on the same page after submitting an HTML form? Long story short, it can only be done with Javascript – Read on for the examples!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
The example code is released under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
SUBMIT FORM WITHOUT RELOADING
All right, let us now get into the examples of how to submit forms without reloading the page.
TUTORIAL VIDEO
THE HTML FORM
<form id="demo" onsubmit="return FUNCTION()">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="email">Email</label>
<input type="email" name="email" required>
<input type="submit" value="Go!">
</form>
- This is the simple HTML form that we will be working with (for all the below examples).
- Take note of
onsubmit="return FUNCTION()"
– We are using Javascript to process the form.
METHOD 1) SUBMIT USING FETCH
1A) FETCH POST
function demoA () {
// (A) GET FORM DATA
var data = new FormData(document.getElementById("demo"));
// (B) SEND FORM DATA TO SERVER
// (B1) FETCH POST
fetch("x-dummy.php", {
method: "post",
body: data
})
// (B2) READ SERVER RESPONSE AS TEXT
.then(res => res.text())
// (B3) DO SOMETHING ON SERVER RESPONSE
.then(txt => {
console.log(txt);
})
// (B4) OPTIONAL - HANDLE ERRORS
.catch(err => console.error(err));
// (C) PREVENT HTML FORM SUBMIT
return false;
}
var data = new FormData(document.getElementById("demo"))
Get data from the HTML form.- Use
fetch()
to send the form data to the server..then(res => res.text())
Read the server response as plain text (string)..then(txt => { console.log(txt); })
What to do with the server response, this is a good place to show a success/failure message..catch(err => console.error(err)}
Optional, handle errors.
return false
To stop the “default submit HTML form” and reloading the page.
1B) FETCH GET
function demoB () {
// (A) GET FORM DATA + URL
var data = new FormData(document.getElementById("demo")),
url = "x-dummy.php?" + new URLSearchParams(data).toString();
// (B) SEND FORM DATA TO SERVER
// (B1) FETCH GET
fetch(url, { method: "get" })
// (B2) READ SERVER RESPONSE AS TEXT
.then(res => res.text())
// (B3) DO SOMETHING ON SERVER RESPONSE
.then(txt => {
console.log(txt);
})
// (B4) OPTIONAL - HANDLE ERRORS
.catch(err => console.error(err));
// (C) PREVENT HTML FORM SUBMIT
return false;
}
If you want to send the form data to the server via GET:
- (A) Create a
var data = new FormData()
object as usual. - (A) But take note, we append the form data to the URL –
var url = "SCRIPT.PHP?" + new URLSearchParams(data).toString()
. - (B1) Change
fetch
tomethod: "get"
.
METHOD 2) SUBMIT USING XMLHTTPREQUEST
2A) XMLHTTPREQUEST POST
function demoC () {
// (A) GET FORM DATA
var data = new FormData(document.getElementById("demo"));
// (B) SEND FORM DATA TO SERVER
// (B1) XML HTTP REQUEST
var xhr = new XMLHttpRequest();
xhr.open("POST", "x-dummy.php");
// (B2) DO SOMETHING ON SERVER REPONSE
xhr.onload = () => {
console.log(xhr.response);
};
// (B3) GO!
xhr.send(data);
return false;
}
- TLDR –
XMLHttpRequest()
is the ancestor offetch()
. - The usage is pretty much the same – Collect HTML form data, create
new XMLHttpRequest()
object, send to server, and handle the server response. - Try to stick with the modern
fetch()
, useXMLHttpRequest()
only for backward-compatibility… It may get deprecated eventually.
2B) XMLHTTPREQUEST GET
function demoD () {
// (A) GET FORM DATA + URL
var data = new FormData(document.getElementById("demo")),
url = "x-dummy.php?" + new URLSearchParams(data).toString();
// (B) SEND FORM DATA TO SERVER
// (B1) XML HTTP REQUEST
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
// (B2) DO SOMETHING ON SERVER REPONSE
xhr.onload = () => {
console.log(xhr.response);
};
// (B3) GO!
xhr.send();
return false;
}
If you want to do a GET submission with XMLHttpRequest
– It is pretty much the same process again. The only difference here is that the data is appended to the URL as a query string.
EXTRAS
That’s all for the code, and are a few small extras that may be useful to you.
ARROW FUNCTIONS
Before the beginners get a panic attack over what is txt => { console.log(txt); }
– These are arrow functions.
function twice (a) { return a * 2; }
You already know this.var twice = function (a) { return a * 2; };
We can also define a function this way.var twice = (a) => { return a * 2; };
In modern Javascript, we can shorten function definitions with the=>
arrow operator.var twice = a => { return a * 2; };
If there is only one parameter, we can omit the round brackets.var twice = a => a * 2;
We can further shorten the function if it only has one line.
AJAX
- Both methods above are known as “AJAX” – Asynchronous Javascript And XML.
- In short, “process in parallel without blocking or reloading the page”.
- Take note – The modern interpretation of AJAX is confusing. So long as data is exchanged with the server asynchronously, it is called “AJAX”. Even though XML is not involved in the exchange.
HOW ABOUT THE SERVER SIDE?
<?php
print_r($_POST);
print_r($_GET);
- It’s up to you to complete the server-side – Save the submitted form data to a database, to a file, send via email, etc…
- In this example, we simply echo what is being submitted.
REFERENCES & LINKS
- Simple AJAX Examples in PHP – Code Boxx
- Promise – MDN
- Fetch API – MDN
- HTML Form Validation – Code Boxx
INFOGRAPHIC CHEAT SHEET
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!
This good
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.