To display a loading spinner during an AJAX request with jQuery, you can use the following steps:
<div id="loading-spinner">Loading...</div>
#loading-spinner {
display: none;
}
ajaxStart
and ajaxStop
events to show and hide the loading spinner. These events will be triggered automatically when an AJAX request starts and stops.$(document).ajaxStart(function() {
$('#loading-spinner').show();
});
$(document).ajaxStop(function() {
$('#loading-spinner').hide();
});
$.ajax()
or $.get()
functions, and wrap your AJAX code inside the beforeSend
and complete
callback functions.$.ajax({
url: 'example.com',
type: 'GET',
beforeSend: function() {
// Show the loading spinner
$('#loading-spinner').show();
},
success: function(response) {
// Do something with the response
console.log(response);
},
error: function(err) {
// Handle the error
console.error(err);
},
complete: function() {
// Hide the loading spinner
$('#loading-spinner').hide();
}
});
Now, the loading spinner will be displayed while the AJAX request is in progress, and it will be hidden once the request is completed.