Is it possible to get the upload-progress for a form with very large textfields using jQuery ajax? I think the client knows how much bytes have been sent, but when I Google I only find solutions for file-uploads using server-site code.
This is my ajax-request:
$.ajax({
type: "POST",
url: "index.php?action=saveNewPost",
data: {textbox1: textbox1,textbox2: textbox2},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(){
//
}
});
I was hoping there would be something like "onProgress" with a parameter containing the amount of bytes already sent...
Found a solution
$.ajax({
xhr: function() {
var req = $.ajaxSettings.xhr();
if (req) {
req.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
$('#ajaxFeedbackDiv').html(event.loaded); // = 'test'; //event.loaded + ' / ' + event.total;
}
}, false);
}
return req;
},
type: "POST",
url: "index.php?action=saveNewPost",
data: {textbox1: textbox1,textbox2: textbox2},
contentType: "application/x-www-form-urlencoded;charset=UTF-8"
}
});
this seems to work, altough there are still
2 problems:
You could achieve this with the new XMLHttpRequest
object in HTML5 capable browsers. It supports the progress
event that you could subscribe to and be notified of the AJAX operation.
Here's an example:
document.getElementById('myForm').onsubmit = function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
document.getElementById('progress').innerHTML = percentage + '%';
}
}, false);
xhr.open(this.method, this.action, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.send(new FormData(this));
return false;
};
and here's a live demo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With