2

This is a follow up question from my previous one "How do I measure a loading time of an AJAX request and display a loading panel?". Now I am wondering how will I suppose to display an animated loading bar/panel like this:

enter image description here

And what I mean is that an actual moving panel from 0% to 100%. I have here a bit of code to begin the discussion. I'm implementing a tutorial loading from this wonderful site.

    $("#connection").click(function(e) {
        e.preventDefault();
        //show_loading();
        $.ajax({
            url: "./home/connect",
            type: 'GET',
            dataType: 'json', 
            progress: function(jqXHR, progressEvent) {
                if (progressEvent.lengthComputable) {
                    console.log("Loaded " + (Math.round(progressEvent.loaded / progressEvent.total * 100)) + "%");
                } else {
                    console.log("Loading...");
                }
            },
            success : function(data) {
                //hide_loading();
                Materialize.toast(data.db_connect, 4000, 'rounded green');
            },
        });
    });

The problem with this code is that it displays 100% in the console the moment it reaches to 100% and not live ( showing the actual counting from 0 - 100 ).

enter image description here

Community
  • 1
  • 1
Hard Spocker
  • 765
  • 11
  • 32
  • 1
    As best I know, the Ajax progress only works for actual data transfer where there are significant enough bytes to transfer that the progress indicator is meaningful about the time to upload or download. The progress event does not cover the time of the ajax response from the server. – jfriend00 Oct 24 '15 at 06:27
  • 1
    lets just say i have a function that counts for 5 seconds, how will i sync the time and the progress bar to reach 100% when timer reach 5 seconds? – Hard Spocker Oct 24 '15 at 06:35

1 Answers1

0

I don't see any progress function in the official docs but I found this code here:

$.ajax({
    url: path,
    xhrFields: {
        onprogress: function (e) {
            if (e.lengthComputable) {
                console.log(e.loaded / e.total * 100 + '%');
            }
        }
    },
    success: function (response) {

    }
});
Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • yeah they are behaving the same. its still just showing my the 100% and not the dynamic counting. @ShanShan – Hard Spocker Oct 24 '15 at 06:12
  • quick question though, can the console render live data feeds? like what we are doing? – Hard Spocker Oct 24 '15 at 06:14
  • Yes, the console works all the time. I think your server just doens't send the size of the response so a progress is not computable. More here: http://stackoverflow.com/questions/22502943/jquery-ajax-progress-via-xhr – Shanoor Oct 24 '15 at 06:16
  • im pretty sure its computable. otherwise it will just log `Loading...`. – Hard Spocker Oct 24 '15 at 07:23