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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago