How to Add an Ajax Loader to Your Website Layout for All Ajax Calls

How to Add an Ajax Loader to Your Website Layout for All Ajax Calls

 

To put an Ajax loader in the layout that works for all Ajax calls, you can follow these steps:

  1. Add a loader element in your layout HTML markup that will be displayed during the Ajax request.
    <div id="ajax-loader" style="display:none;">
      <img src="/path/to/ajax-loader.gif" alt="Loading..." />
    </div>
    

     

  2. Create a JavaScript file to handle the Ajax calls and show/hide the loader element. In this file, add the following code:
    $(document).ajaxStart(function() {
      $('#ajax-loader').show();
    });
    
    $(document).ajaxStop(function() {
      $('#ajax-loader').hide();
    });
    

    The ajaxStart() function is called when an Ajax request starts, and the ajaxStop() function is called when all Ajax requests have completed.

  3. Create a JavaScript file to handle the Ajax calls and show/hide the loader element. In this file, add the following code:
    <script src="/path/to/jquery.min.js"></script>
    <script src="/path/to/ajax-handler.js"></script>
    

     

  4. Finally, add some CSS styling to your loader element to make it look more visually appealing.
    #ajax-loader {
      display: block;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #ffffff;
      border-radius: 5px;
      padding: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
    }
    
    #ajax-loader img {
      display: block;
      margin: 0 auto;
    }
    

By following these steps, you can easily add an Ajax loader in the layout that works for all Ajax calls. Whenever an Ajax request is made, the loader element will be displayed, and when the request is completed, the loader element will be hidden automatically.

Another Way

$.ajax({
  type: "POST",
  url: "/Controller/Action",
  data: { /* your data */ },
  beforeSend: function () {
    $('#loader').show();
  },
  success: function (result) {
    $('#loader').hide();
    // handle success response
  },
  error: function (xhr, status, error) {
    $('#loader').hide();
    // handle error response
  }
});

 

Similar Posts