8
$.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); //Upload progress xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; //Do something with upload progress console.log(percentComplete); } }, false); //Download progress xhr.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; //Do something with download progress console.log(percentComplete); } }, false); return xhr; }, type: 'POST', url: "/", data: {}, success: function(data){ //Do something success-ish } }); 

This does not work on jQuery 1.5+ because the xhr is replaced by the jqXHR (i.e. a high level version of the raw XHR.) Now the question is how to get it to work with jqXHR… Anyone know how to do it?

2
  • I don't think this is a duplicate of the given post, the given post doesn't even use jQuery, and jQuery is the cause of this problem. Commented Nov 2, 2012 at 21:34
  • As of jQuery 1.5, $.ajax() returns a jqXHR object, which implements the Promise interface. I guess that you can monitor progress with '$.ajax(...).progress(callback). Unfortunately, I can't find a full refernce so can't advise of what parameters the callback accepts, though it's probably the same as a done` (success) callback, ie. function(data, textStatus, jqXHR){...}. The jqXHR Object exposes a bunch of properties and methods which can be exploited in the callback. Commented Nov 3, 2012 at 0:56

3 Answers 3

12

Try this

$.ajax({ url: path, xhr: function () { var xhr = $.ajaxSettings.xhr(); xhr.upload.onprogress = function (e) { if (e.lengthComputable) { console.log(e.loaded / e.total); } }; return xhr; } }).done(function (e) { }) 
Sign up to request clarification or add additional context in comments.

Comments

4

I made a jquery plugin to handle upload or download progress events in a easy way. Works any jquery ajax method such as $.ajax, $.get, $getJSON, $.post, etc. You can download it from here: https://github.com/cvelazquez/jquery.ajax.progress

var jqXHR = $.post('www.somedomain.com', {data:"real long data, o maybe a file upload"}, function(response){ /* do anything on finish */ }); $(jqXHR).on('uploading', function(proxyEvent, event){ if (event.lengthComputable) { // You can do anything here console.log("Uploaded " + parseInt( (event.loaded / event.total * 100), 10) + "%"); } }); 

Comments

1

Searching around the documentation and other questions, there appears to be a plugin to monitor the jquery ajax progress: https://github.com/hiddentao/jquery.ajaxprogress

1 Comment

The plugin you linked does not provide percentages, only an indicator if the upload is in progress or not. Not helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.