Lovelock
Lovelock

Reputation: 8075

Generating a loading bar / percentage when AJAX image upload

I have an image upload feature that works like this:

$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
var formData = new FormData($('.update-insertimage-form')[0]);
$.ajax({
    url: rootAsset+'saveUploadedImage',
    type: 'post',
    cache: false,
    dataType: 'json',
    data: formData,
    processData: false,
    contentType: false,
    beforeSend: function() {
      $(".form-control-addupdate").append('<div class="uploading-overlay">Uploading Image...</div>');
      $(".uploading-overlay").fadeIn();
    },
    success: function(data) {
      $(".submit-newupdate-btn").removeClass('disabled');
      if(data.errors) {
        $('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
      } else if (data.success) {
        $(".form-control-addupdate").append('<img class="temp_added_image" src="/public_html/user_uploads/build_images/'+data.name+'.jpeg"><br><br>');
        $(".uploading-overlay").fadeOut(function(){
          $(".uploading-overlay").remove();
        });
        var $t = $('.form-control-addupdate');
        $t.animate({"scrollTop": $('.form-control-addupdate')[0].scrollHeight}, "slow");
      }
    },
    error: function(xhr, textStatus, thrownError) {
        alert('Something went to wrong.Please Try again later...');
    }
});
return false;
});

Instead of just 'Uploading Image' I want to show the user a percentage or a loading bar etc. I have searched around but cannot find much information. My thoughts so far are tracking when the ajax call is made and then when the success call back is returned. But no idea how to generate a loading percentage etc.

I would rather use a percentage number as apposed to a loading bar, and it can be a 'fake' number just so long as it increases and finishes at 100% when the image is uploaded.

Thanks!

EDIT: Just to make it clear, I dont need a specific and real percentage. Just a way of increasing from 1 - 100% from the point the call is made to it being received.

Upvotes: 0

Views: 1726

Answers (1)

Codermonk
Codermonk

Reputation: 883

You'll want to include the xhr option in the AJAX request and add an Event Listener to track the progress of the request:

xhr: function() {
                var xhr = new window.XMLHttpRequest();
                xhr.addEventListener('progress', function(e) {
                     $('.progressbar .bar').css('width', '' + (100 * e.loaded / e.total) + '%');
                     $('.progresspercent').text((100 * e.loaded / e.total) + '%');
                });
                return xhr;
            },

Where progressbar and progresspercent are elements in your HTML

Upvotes: 4

Related Questions