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.