简体   繁体   中英

How to put a loader in ajax requests?

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(),
    }); 
    });
});

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

   <img 
        src="https://thumbs.gfycat.com/PessimisticGlamorousDunnart-size_restricted.gif" 
        class="loader" 
        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();
            }
          });
        });
    });

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM