Handle Multi Form Upload using JavaScript and Ajax
Using JavaScript we can Handle Multi Form Upload
I recently built a multi form upload using JavaScript and AJAX and I will share with you the process below.
Say you have an App that allows the upload of staff profile data in your company, this can be a daunting process if you have to singly upload the data of 20 or more staff members. But here's good news, using Arrays would save you much time.
How do I begin?
HTML
Lets create a simple form with the fields below.
- First Name
- Last Name
- Email Address
<button id="btn_save" type="button">Save</button>
<form id="form_multi_upload" method="POST">
<input id="inp_fname" type="text" name="fname">
<input id="inp_fname" type="text" name="lname">
<input id="inp_email" type="email" name="email">
<button id="btn_submit" type="submit">Upload</button>
</form>
Notice that there's a save button on the form above. This button will enable us continually save the data into the arrays that we will declare below.
JAVASCRIPT
I will begin with basic JavaScript. We have to declare Arrays that will hold the data of each of the fields above that we need from the user.
var fnameArry = [];
var lnameArry = [];
var emailArry = [];
Now that we have declared their Arrays, we need to create a function that will accept the form inputs and store them into the Arrays, taking note of duplicate records. Don't worry! Its easy peasy.
saveForm()
Lets begin with the function
function saveForm(fname, lname, email) {
//Save form inputs to our Array
fnameArry.push(fname);
lnameArry.push(lname);
emailArry.push(email);
}
Notice that we declared our function arguments to accept 3 parameters which are the (first name, last name and email). So our save button will come in handy now.
Let's use an Event listener monitor the save button and perform an action when the button is clicked.
document.addEventListener('DOMContentLoaded', (event) => {
document.querySelector('#btn_save').addEventListener('click', function() {
var fname = document.querySelector('#inp_fname').value;
var lname = document.querySelector('#inp_lname').value;
var email = document.querySelector('#inp_email').value;
saveForm(fname, lname, email);
});
})
Using JQUERY , you can simplify the code above
$(document).ready(function() {
$('#btn_save').on('click', function(){
var fname = $('#inp_fname').val();
var lname = $('#inp_lname').val();
var email = $('#inp_email').val();
saveForm(fname, lname, email);
});
})
Now we have achieved 50% of our GOAL. Lets make it 100%.
The Save button has been instructed that when it is clicked, save any form input available to their respective Arrays.
Notice that we didn't include a check to make sure all fields are filled out (contain values).
This will be really important cause we don't want to upload data that are not related.
We can edit our function to check that easily.
function saveForm(fname, lname, email) {
//Check form fields
if(!fname){
alert('First Name is required');
}else if(!lname){
alert('Last Name is required');
}else if(!email){
alert('Email Address is required');
}else{
//Save form inputs to our Array
fnameArry.push(fname);
lnameArry.push(lname);
emailArry.push(email);
}
}
We've updated our function to check for form fields and then continue if all inputs are met.
But then we also have to check for duplicate records. How do we go about it?
Well it's easy again. Let's use includes() JavaScript method to achieve this.
function saveForm(fname, lname, email) {
//Check form fields
if(!fname){
alert('First Name is required');
}else if(!lname){
alert('Last Name is required');
}else if(!email){
alert('Email Address is required');
}else{
//Check for duplicate records then save
if (fnameArry.includes(fname)){
alert('Duplicate First Name Detected');
}else if(lnameArry.includes(lname)){
alert('Duplicate Last Name Detected');
}else if (emailArry.includes(email)){
alert('Duplicate Email Address Detected');
}else{
//Save form inputs to our Array
fnameArry.push(fname);
lnameArry.push(lname);
emailArry.push(email);
}
}
You can make the code above more advanced using a Nested Tenary Operation
function saveForm(fname, lname, email) {
//Check form fields
if(!fname){
alert('First Name is required');
}else if(!lname){
alert('Last Name is required');
}else if(!email){
alert('Email Address is required');
}else{
//Check for duplicate records then save
(fnameArry.includes(fname)) ?
alert('Duplicate First Name Detected') :
(lnameArry.includes(lname)) ?
alert('Duplicate Last Name Detected') :
(emailArry.includes(email)) ?
alert('Duplicate Email Address Detected') :
//Save form inputs to our Array
fnameArry.push(fname);
lnameArry.push(lname);
emailArry.push(email);
}
}
I talked about Nesting a Tenary Operation and here, you can make good use of it. If you notice, the else and else if() keywords were not needed again because we have used a tenary operator (:) to replace it.
You can learn more about it by revisiting the post.
ALMOST DONE
Now we are 95% Close to our GOAL. Let's give it a 5% push shall we ?
We have our Array that stores the form inputs, how do we alert the user that he has saved x number of records so far?
Well since our Array accepts records that must contain input, their lengths (total number of records inside) have to be the same. That means, they are all equal.
You could create an HTML Element on your page
<p> You have Saved <span id="inp_count"> </span> records so far </p>
Then in your function Using JQUERY OR NATIVE
function saveForm(fname, lname, email) {
//Check form fields
if(!fname){
alert('First Name is required');
}else if(!lname){
alert('Last Name is required');
}else if(!email){
alert('Email Address is required');
}else{
//Check for duplicate records then save
if (fnameArry.includes(fname)){
alert('Duplicate First Name Detected');
}else if(lnameArry.includes(lname)){
alert('Duplicate Last Name Detected');
}else if (emailArry.includes(email)){
alert('Duplicate Email Address Detected');
}else{
//Save form inputs to our Array
fnameArry.push(fname);
lnameArry.push(lname);
emailArry.push(email);
}
//Total Number of records. Since they are equal, choose one array
document.querySelector('#inp_count').innerText = fnameArry.length;
}
You could also prevent the form from submitting until total records is greater than 1, in that way, they are uploading a multi record.
AJAX
We have set up our logic, now it's time to submit. Depending on the language you're using, I guess the process is still the same
/* AJAX FORM SUBMIT */
$('#form_multi_upload').submit(function (event){
event.preventDefault();
var formData = {
fname : fnameArry,
lname : lnameArry,
email : emailArry
};
$.ajax({
type: "POST",
url: "MY_API_URL_HERE",
data: formData,
dataType: "json",
encode:true,
success: function success() {
//Success Action Here
},
error: function error(xhr){
//Error Action Here
}
});
});
SERVER SIDE
You may now use foreach to process the records one after the other!
EXTRA
- You may consider using a function to store the data to the browser's storage area to prevent loss of saved records on browser reload
- You may also consider notifying a user that saved records would be lost if they don't upload when they try to reload their broswer.
We made it to 100% !
How would you implement this Function on your Code ?
Feel free to drop a Comment below if you need help with understanding the post.
Thank You !