5

I am new to jQuery and now, I am currently working on file uploads. And I want to add some progress bar each time I upload image. I used the uploadProgress in jQuery but it seems doesn't work. Here's my code:

$('#_form_').on('submit', function(e){

   var file_and_desc = new FormData($(this)[0]),
       form_url = "_pages/_form_";

       var ext = choose.val(),
           allowed = ['jpg','png'];

       if(ext){
          var get_ext = ext.split('.');
              get_ext.reverse();

              if($.inArray(get_ext[0].toLowerCase(), allowed) > -1){
                   //upload image
                   $.ajax({
                         url : form_url,
                         type: 'POST',
                         data: file_and_desc,
                         contentType: false,
                         processData: false,
                         uploadProgress: function(event, positio, total, percentComplete){
                          $('h1').html(percentComplete);
                         },
                         success: function(data){
                              // some code here...
                         }
                   });
              }
       }
});

That's it! What should I do?

Trish Siquian
  • 495
  • 3
  • 11
  • 22
  • Possible duplicate of [What is the cleanest way to get the progress of JQuery ajax request?](http://stackoverflow.com/questions/19126994/what-is-the-cleanest-way-to-get-the-progress-of-jquery-ajax-request) – tklg Feb 14 '17 at 02:10
  • @Villa7_, You're confusing my mind! It doesn't help – Trish Siquian Feb 15 '17 at 05:33

1 Answers1

22

According to the $.ajax() reference, uploadProgress is not a valid option.

Instead, the xhr option is used instead, which lets you set progress listeners on the XMLHttpRequest that is used by the ajax request.

this answer shows how to do that:

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                //Do something with upload progress here
            }
       }, false);
       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        //Do something on success
    }
});
Community
  • 1
  • 1
tklg
  • 2,572
  • 2
  • 19
  • 24
  • Thanks so much bud! Saved my day. – JuliSmz Dec 03 '19 at 16:09
  • 1
    I think it is a valid reference if you have the jQuery form plugin installed. http://jquery.malsup.com/form/ – Tom Jan 30 '21 at 04:20
  • I noticed that you created the xhr object using "window.XMLHttpRequest" rather than just simply "XMLHttpRequest". That was the missing piece of the puzzle for me. – Vincent Apr 03 '23 at 16:41