Home > Enterprise >  How can I put a loader in my ajax requests?
How can I put a loader in my ajax requests?

Time:09-14

One is a small code that allows me to view error messages when the form fields are empty or when everything is fine. What I would like to do is enter a loader or text to indicate that the submitted action is being processed. I really don't know where to start, can someone help me understand how to achieve this?

jQuery(document).ready(function($) {
    
    $('.mts-edit-account').on('submit', function(e) {
        e.preventDefault();

    //Ajax Handling Error
        var $form = $(this);
        jQuery.post(
      $form.attr('action'), 
      $form.serialize(), 
      function(data) {
        jQuery('.newdiv').html(data);
          }, 'json',
      
    );

    //Ajax function
    jQuery.ajax({
      type: "post",
      data: jQuery(".mts-edit-account").serialize(),
    }); 
    });
});

CodePudding user response:

AJAX requests using jQuery allows you to handle request completion, failure or success using the returned value from ajax() function. In your case you need to start by showing the loader before starting the request, then hide on completion. To do that, you can use always() function. That will make sure it's always called in case of success or failure.

// Show loader
jQuery.ajax({
    // ..
}).always(() => {
    // Hide loader
});

CodePudding user response:

Firstly put the loader in your HTML file where you want to display it. i.e: below the submit button

   <img 
        src="https://thumbs.gfycat.com/PessimisticGlamorousDunnart-size_restricted.gif" 
         
        alt="Loader"
        height=25 
        width=25 
    >

Then add CSS for this loader:

  .loader{
      display:none;
   }

Then put the below code in jQuery:

    jQuery(document).ready(function($) {
        $('.mts-edit-account').on('submit', function(e) {
          e.preventDefault();
          $.ajax({
            type: "POST",
            url: "your_url",
            data: $(".mts-edit-account").serialize(),
            beforeSend: function() {
               $(".loader").show();
            },
            success: function(msg) {
              $(".loader").hide();
            }
          });
        });
    });
  • Related