Creating a loading div and hiding it - Ajax with loader

26 0 0 0

Last Updated : 2020-09-18 11:31:35

Here is a snippet for a function to create a loader or a loading div to be used with ajax request and then can also hide it.

const APP_URL="http://localhost/jay/goviq/public/";


const loader = (targetElId='', where="beforeEnd") => {

id = 'loader';
const targetEl = (targetElId != '') ? document.getElementById(targetElId) : document.body ;

const oldEl = document.getElementById(id);
if(oldEl) {
oldEl.remove();
}

const loadingEl = document.createElement('div');
loadingEl.id = id;
loadingEl.className = '';
loadingEl.style = "text-align: center;";
loadingEl.innerHTML = `<img src='${APP_URL}images/loadingH.gif' style='margin: auto;'/>`;

where = (where != '') ? where : "beforeEnd" ;
targetEl.insertAdjacentElement(where, loadingEl);
//return loadingEl;
return loadingEl.id;

/*
//The following code will work on a div in the modal that contains the image itself.
const loaderDiv = document.getElementById('loaderDiv');
console.log(loaderDiv);
loaderDiv.style.display= 'block'; */
}

const Removeloader = (loaderElId = '') => {
loaderElId = (loaderElId != '') ? loaderElId : 'loader' ;
document.getElementById(loaderElId).remove();
/* const loaderDiv = document.getElementById('loaderDiv');
loaderDiv.style.display= 'none'; */
}

And Here is a complete ajax example on how and where to use these two JS functions


$.ajax({
type: "post",
url: "{{ URL('admin/billFederalEvents/update') }}/"+itemId,

processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType

async: true,
cache: false,
enctype: 'multipart/form-data',

data:formData,
beforeSend: function(){
loader('theBTN', "afterBegin");
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//dataType: "json",
success: function (msg) {
if (msg) {

if(msg['myResponseStatus']) {
$("#modalResponseDiv").html(msg['myResponseMessage']).show();

setTimeout(function(){
$('#constituenciesModal').modal('hide');
$("#modalResponseDiv").html("").hide();

//Reload the page
window.location.reload();
}, 3000);

$("#constituenciesModal #editForm").trigger("reset"); //reset the form
} else {
alert('there is no response status') ;
}

} else {
alert("Cannot add to list !");
}
},
}).done(function(msg){
Removeloader();
});

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .