Categories: Development

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.

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">
    </div>
</div>

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
        $.ajax({
            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).

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago