Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cleanest way to get the progress of JQuery ajax request?

In plain javascript is very simple: need just to attach the callback to {XMLHTTPRequest}.onprogress

var xhr = new XMLHttpRequest();  xhr.onprogress = function(e){     if (e.lengthComputable)         var percent = (e.loaded / e.total) * 100; };  xhr.open('GET', 'http://www...', true); xhr.onreadystatechange = function() {     ... }; xhr.send(null); 

but I'm doing an ajax site that download html data with JQuery ($.get() or $.ajax()) and I was wondering which is the best way to get the progress of a request in order to display it with a little progress bar but curiously, I'm not finding anything usefull in JQuery documentation...

like image 439
guari Avatar asked Oct 01 '13 22:10

guari


People also ask

How check AJAX request is successful jQuery?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });

When working with AJAX which is faster?

They are all equally fast, the only question is which you find most readable. If you will be making numerous similar ajax calls then it is best to use $. ajaxSetup() in an accessible place (read: near top).


2 Answers

Something like this for $.ajax (HTML5 only though):

$.ajax({     xhr: function() {         var xhr = new window.XMLHttpRequest();         xhr.upload.addEventListener("progress", function(evt) {             if (evt.lengthComputable) {                 var percentComplete = evt.loaded / evt.total;                 //Do something with upload progress here             }        }, false);         xhr.addEventListener("progress", function(evt) {            if (evt.lengthComputable) {                var percentComplete = evt.loaded / evt.total;                //Do something with download progress            }        }, false);         return xhr;     },     type: 'POST',     url: "/",     data: {},     success: function(data){         //Do something on success     } }); 
like image 86
mattytommo Avatar answered Sep 23 '22 01:09

mattytommo


jQuery has already implemented promises, so it's better to use this technology and not move events logic to options parameter. I made a jQuery plugin that adds progress promise and now it's easy to use just as other promises:

$.ajax(url)   .progress(function(){     /* do some actions */   })   .progressUpload(function(){     /* do something on uploading */   }); 

Check it out at github

like image 41
likerRr Avatar answered Sep 21 '22 01:09

likerRr