How to display a loading spinner during an AJAX request with jQuery?

To display a loading spinner during an AJAX request with jQuery, you can use the following steps:

  1. Create a loading spinner HTML element in your HTML file. For example, you can use a spinner element from a CSS library or create your own spinner element. Make sure to give it a unique ID, such as "loading-spinner".
<div id="loading-spinner">Loading...</div>
  1. Hide the loading spinner by default using CSS. You can achieve this by setting the CSS display property to none.
#loading-spinner { display: none; }
  1. Use the jQuery 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(); });
  1. Make your AJAX request using jQuery's $.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.