Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Ajax Request with Percentage

I need to get the % completion for ajax request.

I tried the following:

$(document).ready(function() {
    $.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);

            xhr.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = (evt.loaded / evt.total) * 100;
                    //Do something with download progress
                    console.log(percentComplete);       
                }
            }, false);

            return xhr;
        },
        url : my_path
    }).done(function(data) {

        console.log(data);
    });
}); 

The problem is how do I check whether the above code is working or not. I always get 100 in the firebug console, I doubt instead of 100 there should be multiple % entries in console.

my_path is a PHP page that returns records from MySQL DB. Is there any way to slow down the process/page rendering to check the functionality?

like image 595
user3555483 Avatar asked May 13 '14 04:05

user3555483


1 Answers

The problem with using DB reads is the size needs to be known first, so you really need a file to test this.

For Downloading (client downloading off from the server), you need to introduce delay, otherwise you're only recourse is to download a huge file.

Try this script, which sets up the correct content length headers and only outputs 50 bytes at a time, with a 1 second delay (you can test it with a relatively small file, woot).

As for Uploading (posting to the server), your only option in this regard is to make it a big file, and discard it when done.

like image 80
Mike Avatar answered Oct 28 '22 09:10

Mike