2

I have an AJAX call with datatype JSON, when run the AJAX call, the percentage of progress is indicated in the 'console.log', but the percentual 100% reached before completing the upload file on disk. How do I sync the percentage with the actual progress of the process? I await answers, thank you!

JavaScript

$(document).on('click','.btnSend',function() {
        var imagem = $(this).closest('img.img-preview');
        if (imagem.length>0)
        {
            img_data = imagem.attr('src'); //base64
            img_size = imagem.attr('size');         
        }
        var myjson_imagem = JSON.stringify({img_data: img_data,img_size:img_size});
        $.ajax
        ({
            type: "POST",
            url: "ajax_upload.php",
            data: {dataimagem:myjson_imagem},
            datatype: 'json',
            complete: function(){
                $("[data-toggle='tooltip']").tooltip();
            },
            cache: false,
            async: true,

            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                xhr.onprogress = function e() {
                    // For downloads
                    if (e.lengthComputable) {
                        console.log((e.loaded / e.total *100|0)+"%");
                    }
                };
                xhr.upload.onprogress = function (e) {
                    // For uploads
                    if (e.lengthComputable) {
                        console.log((e.loaded / e.total *100|0)+"%");
                    }
                };
                return xhr;
            },

            success: function(response)
            {
                console.log(response);                                                              
                var obj = JSON.parse(response);         
                var result = obj[0].ajax_result;
                switch (result)
                {
                    case "0": console.log('upload ok'); break;
                    case "1": console.log('upload not ok'); break;

                }
            },
            error: function()
            {
                alert('ajax error UPLOAD');
            }
        });
    });

Log

scriptx.js:1225 3%
scriptx.js:1225 97%
scriptx.js:1225 100%
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
Fábio Zangirolami
  • 1,856
  • 4
  • 18
  • 33

1 Answers1

1

I recently used a similar ajax function where I handled a progress bar for a file uploader. I didn't run into any issues with it reaching 100% before the upload had fully completed. I have included an example below.

    xhr: function() {
                var xhr = $.ajaxSettings.xhr() ;
                // set the onprogress event handler
                xhr.upload.onprogress = function(evt) { 

                    let percentComplete = evt.loaded / evt.total*100+'%';
                    console.log(percentComplete);
};

I hope this helps.

d3ucalion
  • 11
  • 4