Categories
JavaScript Answers

How to Display a Loading Indicator When Making an Ajax Request with jQuery?

Spread the love

To display a loading indicator when making an Ajax request with jQuery, we can use the ajaxSetup method to show and hide the loading indicator before the request starts and when it finishes respectively.

For instance, we can add the loading indicator by writing:

<div id='loading'>
  loading
</div>

Then we can call the ajaxSetup method and then make the request by writing:

$.ajaxSetup({
  beforeSend: () => {
    $("#loading").show();
  },
  complete: () => {
    $("#loading").hide();
  }
});

$.ajax({
  type: 'GET',
  url: 'https://yesno.wtf/api',
})

We call ajaxSetup to add code that runs with all Ajax request made with ajax unless we specify otherwise.

beforeSend is run before the request is made, so we call $(“#loading”).show(); to show the loading indicator.

complete is run before the request is made, so we call $(“#loading”).hide(); to hide the loading indicator.

Then when we call ajax to make the Ajax request, we see the loading indicator shown and then hidden.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *