简体   繁体   中英

Display loading.gif while uploading a file using jQuery

How to show loading.gif while uploading a file using jQuery?

<input type="file" class="form-control" name="profilepic" id="profilepic" accept="image/*" required >
<div id="loader_img"></div>

<button type="submit" name="submit" id="submit" class="btn btn-primary"><span class="glyphicon glyphicon-check"></span> Save</button>

When I click on the save button, loading.gif has to be shown while loading a file.

This is my jQuery:

<script>
$(function() {
  $('form[name="chngimg"]').find('input,select,textarea').not('[type=submit]').jqBootstrapValidation({
    submitSuccess: function ($form, event) {

      $.ajax({
            type: "POST",
            url: "propicchng.php",
            data: $('form').serialize(),
            success: function(msg){
             $('#loader_img').show();

                          // just to confirm ajax submission
          $("#imgchng").modal('hide');
                    alert(msg);
                    $( '#chngimg-form' ).each(function(){
                     this.reset();
                     });},
            error: function(){
                alert("failure");
                }
                });
      event.preventDefault();
    }
  });
});
</script>

What @Mehran Torki is saying is that you need to first put the loader to show before the request - and then hide it in success callback. This is how your code should look like to show the loader - mind the comments!

$(function() {
  $('form[name="chngimg"]').find('input,select,textarea').not('[type=submit]').jqBootstrapValidation({
    submitSuccess: function ($form, event) {
      //here - showing loader to the user
      $('#loader_img').show();
      $.ajax({
        type: "POST",
        url: "propicchng.php",
        data: $('form').serialize(),
        success: function(msg){
          //here - hiding when request is done
          $('#loader_img').hide();
          // just to confirm ajax submission
          $("#imgchng").modal('hide');
          alert(msg);
          $( '#chngimg-form' ).each(function(){
            this.reset();
          });},
        error: function(){
          alert("failure");
        }
      });
      event.preventDefault();
    }
  });
});

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