INTRODUCTION
THE MODERN SUBMIT
Welcome to a tutorial on how to submit a form without refreshing the page. So you have picked up the code ninja skills to submit and process a form. But the stone age of the Internet is long over, and there are better ways to do it – Without reloading the entire page.
Just how do we do that? With AJAX. This guide will walk you through the exact steps on how to do it, with examples in both vanilla Javascript plus jQuery. Read on to find out!
I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
CONFESSION
AN HONEST DISCLOSURE
Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!
NAVIGATION
TABLE OF CONTENTS
Section A | Section B | Extra |
Closing |
SECTION A
VANILLA JAVASCRIPT SUBMIT
Let us start with the pure Javascript and Html version of AJAX form submission first.
STEP 1) THE HTML
Submit Form No Refresh Demo
You should already be familiar with HTML forms, and yes, this is nothing but a simple form here – Except that we add an onsubmit
to the to “intercept” the default form submission, and process our own Javascript.
STEP 2) THE JAVASCRIPT
function doRegister () {
/* [PART 1 - CHECKS] */
// Even though the HTML will do some basic checks
// It is still good to do some of your own
var checks = {
name : document.getElementById("r-name"),
email : document.getElementById("r-email"),
pass : document.getElementById("r-pass"),
cpass : document.getElementById("r-cpass")
},
error = "";
// Name check
if (checks.name.value=="") {
error += "Please enter your name\n";
}
// Email check
var pattern = /^(([^()\[\]\\.,;:\s@"]+(\.[^()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!pattern.test(checks.email.value.toLowerCase())) {
error += "Please enter a valid email\n";
}
// Password check
// You can impose a minimum password length here
if (checks.pass.value.length
Heck. The Javascript to process the form submission may look complicated, but it is actually very straightforward if you walk through it part by part.
- First, we do some checks on the user input, which is kind of optional. HTML actually provides a pretty robust checking system with properties –
required
,type
,maxlength
,pattern
, etc… We are adding Javascript checks here only because HTML cannot match/confirm the passwords. I shall leave it up to you to decide whether Javascript checks are necessary for your own project. - If the checks pass, we process the form via an AJAX call, which runs in the background instead of posting and refreshing the entire page. For those do not know, AJAX stands for Asynchronous Javascript And XML. I shall leave a link to my other guide in the extra section if you are interested to read more.
- That’s it. Just remember to
return false
at the end of it, to prevent the form from being submitted.
STEP 3) SERVER-SIDE SCRIPT
count($error)==0 ? 1 : 0,
"error" => $error
]);
The final piece of the puzzle is to process the POST
data on the server-side and respond back to the Javascript accordingly.
- Do the form checks… again. Actually, you can be lazy to skip the checks on the HTML and Javascript, but I will recommend to always do server-side checks.
- Save the
POST
data, or process it accordingly. - Finally, respond back to the client side – This can be a simple
echo "ok"
, but I like to give a little more details on what went wrong with a JSON encoded array.
SECTION B
JQUERY SUBMIT
Next, we move on with the jQuery way. Which is pretty much the same, except that we will be using… jQuery.
JQUERY JAVASCRIPT
function doRegister () {
/* [PART 1 - CHECKS] */
// Even though the HTML will do some basic checks
// It is still good to do some of your own
var checks = {
name : $('#r-name'),
email : $('#r-email'),
pass : $('#r-pass'),
cpass : $('#r-cpass')
},
error = "";
// Name check
if (checks.name.val()=="") {
error += "Please enter your name\n";
}
// Email check
var pattern = /^(([^()\[\]\\.,;:\s@"]+(\.[^()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!pattern.test(checks.email.val().toLowerCase())) {
error += "Please enter a valid email\n";
}
// Password check
// You can impose a minimum password length here
if (checks.pass.val().length
EXTRA
DOWNLOAD & MORE
That’s all for the code, and here is the download link as promised – Plus a small extra that may be useful to you.
THE SUMMARY
- Build your HTML form. Remember to define the
onsubmit
property to “intercept” the submission with a Javascript function. - Javascript – Do your own checks if you want, then fire an AJAX request to the server.
- Server-side – Check the
POST
data, process it, and respond accordingly.
FORM VALIDATION
Need more help with the form validation? Read my other guide:
Form Validation Using Javascript & HTML (Example Code Included)
VANILLA AJAX
Just what the heck is AJAX, and what does it do? Check out my other guide:
Vanilla Javascript AJAX Tutorial (Learn With Examples)
EXAMPLE CODE DOWNLOAD
Click here to download all the example 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.
CLOSING
TO CHECK OR NOT TO CHECK?
Thank you for reading, and we have come to the end of this guide. Form checks using HTML, form checks in Javascript, then form checks with PHP again. Is that really necessary? Well, no. It really depends on how secure you want your system to be, but at the very least, I will recommend to always do the server-side checks – That cannot be tempered by the users and will serve to protect your systems well.
I hope that this has helped you in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
The post 3 Steps to Submit a Form Without Refreshing Page appeared first on Code Boxx.