EBAG
EBAG

Reputation: 22561

AJAX read data in a progressive manner not just when it's completed

I like to create a progress bar for my ajax calls. For this I can make my server side script to return the state of it's progress. So I need for javascript to read this progress level and show it.

Is it possible or am I on the wrong road?

Upvotes: 3

Views: 408

Answers (2)

Ken Redler
Ken Redler

Reputation: 23943

You could try something like this (some pseudocode, assuming jQuery, since you've tagged the question as such):

var poll;
$.ajax({
  url: 'your_ajax_script',
  beforeSend: function(){ // set up out-of-band status polling
    poll = setInterval( function(){
      $.get('your_script_that_returns_status',
        function(data){ 
          update_progressbar(data);
        });
      }, 1000 ); // update every second?
  },
  success: function(data) {
    clearInterval( poll ); // stop polling
    finalize_or_hide_progressbar(); // clean up
    do_something_with( data ); // your "done" logic
  }
});

Upvotes: 1

Stefan Kendall
Stefan Kendall

Reputation: 67832

Either poll at intervals, returning the payload on the final successful call, or run two AJAX calls - the first retrieving the actual data, and the second polling for update percentage.

Upvotes: 0

Related Questions