JavaScript AJAX Add an AJAX preloader

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Here's a way to show a GIF preloader while an AJAX call is executing. We need to prepare our add and remove preloader functions:

function addPreloader() {
  // if the preloader doesn't already exist, add one to the page
  if(!document.querySelector('#preloader')) {
    var preloaderHTML = '<img id="preloader" src="https://goo.gl/cNhyvX" />';
    document.querySelector('body').innerHTML += preloaderHTML;
  }
}

function removePreloader() {
  // select the preloader element
  var preloader = document.querySelector('#preloader');
  // if it exists, remove it from the page
  if(preloader) {
    preloader.remove();
  }
}

Now we're going to look at where to use these functions.

var request = new XMLHttpRequest();

Inside the onreadystatechange function you should have an if statement with condition: request.readyState == 4 && request.status == 200.

If true: the request is finished and response is ready that's where we'll use removePreloader().

Else if false: the request is still in progress, in this case we'll run the function addPreloader()

xmlhttp.onreadystatechange = function() {

  if(request.readyState == 4 && request.status == 200) {
    // the request has come to an end, remove the preloader
    removePreloader();
  } else {
    // the request isn't finished, add the preloader
    addPreloader()
  }

};

xmlhttp.open('GET', your_file.php, true);
xmlhttp.send();


Got any JavaScript Question?