Ajax progress not working properly - javascript

I have a small problem here. I'm uploading some image data via AJAX to my PHP script. The entire script works well except the progress part.
The only thing in console I get is
Upload1
then
Ajax done
Javasript:
$.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("upload"+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("download:"+percentComplete);
}
}, false);
return xhr;
},
type: "POST",
url: url,
data: {
image: img,
designID: dID,
}
}).done(function( newID ) {
console.log("ajax done");
});
I assumed the upload would count up from 1 to 100%. I tried to do some loops but it didn't work.. Any idea what's happening
Cheers

Add async:true in your ajax request.
$.ajax({
xhr: function(){...},
type: "POST",
url: url,
async: true,
data: {
image: img,
designID: dID,
}
}).done(function( newID ) {
console.log("ajax done");
});

Related

ajax call xhr shows 100% before the code reaches success

I am implementing an ajax progress bar, but the xhr shows 'Uploading 100%' instantly, even though ajax success function is still not called.
$.ajax({
data: //data,
type: 'post',
url: url,
async: false,
xhr: function() {
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
$('#status').html('<b> Uploading -> ' + (Math.round(percentComplete * 100)) + '% </b>');
}
}, false);
return xhr;
},
},
success: // code
};

How to display progress info on console for video-uploading on S3?

I am uploading video on a S3 bucket and would like to see the progress bar.
So i coded :
reader.onload = function (e) {
var rawData = reader.result;
$.ajax({
url: S3url,
type: 'PUT',
cache: false,
processData: false,
data: rawData ,
async: false,
success: fnSuccess,
error: fnError,
crossDomain: true,
contentType: "binary/octet-stream",
xhr: function() {
console.log("xhr");
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
}
}, false);
return xhr;
},
}, 'json'); //$.ajax({
}; //reader.onload = function
But the percent is not displayed in the console.log.
Any Idea ?
xhr should be $.ajaxSettings.xhr() instead of a new instance of XMLHttpRequest() see Upload multiple image using AJAX, PHP and jQuery

jQuery Ajax hangs on large file uploads

I am developing an image hosting website that will send an image over to the server via ajax from jQuery.
If I send a large file, for some weird reason the complete option takes a while to do anything, yet in Developer Tools for Chrome, the Network tab shows me that the request completed and returns anything it should return (In this case, if an image is >20MB, it'll return "File too large" in json format.)
What is the best method to tell ajax to run through it's reporting process once a request is complete, regardless if the file was too large or failed?
This is the code I have so far:
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(evt)
{
if(evt.lengthComputable)
{
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('#btn-upload').fadeOut();
$('.progress-circle').delay(500).fadeIn('fast');
progressCircle.animate(percentComplete / 100);
}
}, false);
return xhr;
},
url: $('form').attr('action'),
type: 'POST',
data: formData,
dataType: 'json',
global: false,
cache: false,
contentType: false,
processData: false,
complete: function(jqXHR)
{
if(jqXHR.readyState === 4)
{
var result = $.parseJSON(jqXHR.responseText);
if(jqXHR.status == 422)
{
$('.progress-circle').fadeOut('fast', function()
{
$('.errors p').html(result);
$('.errors').delay(500).fadeIn('fast');
});
}
else
{
window.location.replace(result.url);
}
}
}
}, 'json');

Get the size of an AJAX response before it finishes loading

I'm using jQuery to load data via AJAX from a server, it's a fairly normal use case. The trick is that I'd like to get the expected content length from the request before it is completed; I want to be able to show a progress bar as the data is loaded.
Is there any way at all to do this? I have to imagine there is. Thanks!
Update: The server has to do quite a bit of work to generate the response, so I'd prefer not to hit it with two requests, it would defeat the purpose.
You can use xhr event in ajax call, and then hook up progress event to that, and check if event.lengthComputable= true, then you will get value, else you will not get value. You can check out following code.
$.ajax({
type: 'POST',
dataType: 'json',
url: URL,
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function (evt) {
console.log(evt.lengthComputable);
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete );
}
}, false);
return xhr;
},
beforeSend: function () {
// before send
},
complete: function () {
// complete.
},
success: function (json) {
// success;
}
});

jQuery Ajax file upload with progress hangs

I'm using jQuery to upload files. Everything worked fine, until I've added xhr: function () {...} code to track file upload progress. Now it just hangs after Start loading image.... If I remove this block from $.ajax, file upload works.
function showProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('.meter').attr({'width': percentComplete + '%'});
}
}
console.log('Start loading image...')
$.ajax({
url: '/uploadimage',
type: 'POST',
xhr: function () {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', showProgress, false);
} else {
console.log("Upload progress is not supported.");
}
return myXhr;
},
//Ajax events
beforeSend: function (xhr) {
// CSRF...
},
success: function (data) {
// do smth
},
// Form data
data: formData,
cache: false,
contentType: false,
processData: false
});
What I'm doing with upload progress wrong? Thanks.
Did you get this resolved? Are you using the upload templates provided or using your own custom markup?
The following works for me:
<script type="text/javascript">
$(document).ready(function () {
$('#btnContinue').prop('disabled', true);
$('#fileupload').fileupload({
url: '#Url.Action("UploadChunk", "Upload")',
maxChunkSize: 1048576,
}).addClass('fileupload-processing')
.bind('fileuploadalways', function (e, data) {
if ($('#fileIds').val().indexOf(';' + data.result.id + ';') == -1) {
var pre = $('#fileIds').val() == "" ? ';' : '';
var append = $('#fileIds').val() + pre + data.result.id + ';';
$('#fileIds').val(append);
}
})
.bind('fileuploaddone', function (e, data) {
$('#btnContinue').prop('disabled', false);
});
$.ajax({
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
});
});
</script>
I do have an issue with my setup, but you should be able to reference my code for what you are trying to achieve.
Submit Additional Form Data without setting formData

Categories