Ajax loading spinner example with Bootstrap

How to do a progress loading spinner whilst waiting for an Ajax call/request.

This can prevent the awkward blank page whilst loading in elements from an HTTP GET request.

ajax spinner while loading bootstrap

CodePen example link.

The spinner HTML element

The first step is to create the spinner div, You could use a gif or a Bootstrap class. I am using the latter.

<div id="spinner-div" class="pt-5">
    <div class="spinner-border text-primary" role="status">

This is nothing fancy it just states the spinner div and then has the actual spinner as another div. Put this below the opening body tag.

The spinner CSS

The CSS has positioning parameters but the most important part is that its display is set to none.

#spinner-div {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 2;

The Javascript

The Javascript is an on click function for the button. This button initializes the Ajax GET request however it also will immediately show the spinner div. This means spinner-div becomes active, there is now a spinner on the page.

Then on the Ajax call complete the spinner div gets hidden. There is no more spinner because the Ajax call has finished.

$(document).ready(function () {
    $("#do-call").click(function () {//The load button
        $('#spinner-div').show();//Load button clicked show spinner
            url: "https://api.domain.com/call/",
            type: 'GET',
            dataType: 'json',
            success: function (res) {
               //On success do something....
            complete: function () {
                $('#spinner-div').hide();//Request is complete so hide spinner

The complete function is used rather than success or error because this means it is guaranteed to fire no matter what the call result was.

The only interaction Javascript has with the spinner is to show and then hide it (on Ajax complete).