1255 0 0 0
Last Updated : 2025-04-28 23:34:48
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();
});