Submit HTML Form Without Reloading (POST & GET)

So, you need to submit a form without reloading the page. Yes, that can be easily done with AJAX (asynchronous Javascript and XML). Let Master Coffee walk you through some simple examples – Let’s go.

 

CODE DOWNLOAD

I have released this under the MIT license, feel free to use it in your own project – Personal or commercial. Some form of credits will be nice though. 🙂

 

 

VIDEO TUTORIAL

 

1) HTML FORM

1-submit.html
<!-- (PART A) HTML FORM -->
<form id="demo" onsubmit="return go();">
  <input type="email" name="email" value="[email protected]" required>
  <input type="submit" value="Go">
</form>

For this example, we will use this dummy form with a single email field. The only thing to take note here is onsubmit="return go();", we will use a Javascript function to manage the submission.

 

 

2) AJAX SUBMIT

2A) WHAT IS AJAX? POST? GET?

TLDR for the lazy ones who skipped the basics:

  • AJAX – “Do processing in parallel”, the form submission will happen in the background while the user continues to use the page.
  • GET – The form data will be appended to the end of the URL. Example – http://site.com/submit?key=value
  • POST – Submit the form silently, the form data is not visible in the URL.

 

2B) SUBMIT VIA POST

2-post.js
// (PART B) JAVASCRIPT SUBMIT FORM
function go () {
  // (B1) GET HTML FORM DATA
  var form = new FormData(document.getElementById("demo"));

  // (B2) SUBMIT FORM VIA POST
  fetch("x-dummy.php", {
    method: "POST",
    body: form
  })
  .then(res => res.text())
  .then(txt => {
    // DO SOMETHING ON SERVER RESPONSE
    console.log(txt);
  })
  .catch(e => console.error(e));

  // (B3) STOP FORM SUBMIT
  return false;
}
  • (B1) Create a form = new FormData() object, feed in the HTML form.
  • (B2) Send the form to the server via POST.
    • fetch() takes in 2 parameters. The URL and options – Where we set the submission method and attach the form data.
    • .then(res => res.text()) Then, return the server response as text.
    • .then(txt => ...) Do something on server response. This is a good place to show if the process succeeded/failed.
    • .catch(e => ...) Optional, handle any errors.
  • (B3) Lastly return false to prevent the default HTML form submit.

 

 

2C) SUBMIT VIA GET

2-get.js
// (PART B) JAVASCRIPT SUBMIT FORM
function go () {
  // (B1) GET HTML FORM DATA
  var form = new FormData(document.getElementById("demo"));
  form = new URLSearchParams(form).toString();

  // (B2) SUBMIT FORM VIA GET
  fetch("x-dummy.php?" + form)
  .then(res => res.text())
  .then(txt => {
    // DO SOMETHING ON SERVER RESPONSE
    console.log(txt);
  })
  .catch(e => console.error(e));

  // (B3) STOP FORM SUBMIT
  return false;
}
  • (B1) It’s the same form = new FormData() object. But we turn it into a query string with new URLSearchParams(form).toString().
  • (B2) Append the form data to the end of the URL fetch("x-dummy.php?" + form).
  • (B2) Also, take note that the options are empty now. It will default to “submit via GET”.
  • (B3) Same. Return false to prevent default form submit.

 

 

2D) SUBMIT VIA XMLHTTPREQUEST

2-xhr.js
// (PART B) JAVASCRIPT SUBMIT FORM
function go () {
  // (B1) GET HTML FORM DATA
  var form = new FormData(document.getElementById("demo"));

  // (B2) AJAX REQUEST
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "x-dummy.php");
  // xhr.open("GET", "x-dummy.php?" + new URLSearchParams(form).toString());
  xhr.onload = () => {
    // DO SOMETHING ON SERVER RESPONSE
    console.log(xhr.status);
    console.log(xhr.response);
  };
  xhr.send(form);

  // (B3) STOP FORM SUBMIT
  return false;
}

Lastly, here is an example using XMLHttpRequest(). For those who are new, XMLHttpRequest() is the “ancestor” of fetch(). At the time of writing, XMLHttpRequest() is not deprecated, so it is still relevant. The usage is pretty much the same as fetch().

  • (B1) Same, start with the FormData().
  • (B2) Submit the form via AJAX.
    • Create a xhr = new XMLHttpRequest() object.
    • Set the method and URL – xhr.open("POST", "x-dummy.php").
    • Do something on server response – xhr.onload = ...
    • Send the form data – xhr.send(form)
  • (B3) Prevent the default form submit.

 

 

THE END – EXCHANGE DATA WITHOUT FORMS

That’s all for this short tutorial and sharing. One last bit of “reminder” to the beginners, we don’t live in the Stone Age of the Internet anymore… We can exchange data with the server at any time, without using any HTML forms.

  • var form = new FormData();
  • form.append("KEY", "VALUE");
  • fetch(...)

 

CHEAT SHEET

Submit HTML Form Without Reloading (click to enlarge)