ajax call xhr shows 100% before the code reaches success - javascript

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
};

Related

'parsererror' error In MYSQL Axaj Django upload in chunks

I want to upload a file in chunks, and it works on SQLite but i wont work with MYSQL, and it uploads the file only till 10mb/11mb. Debug false/true gives me the same error
JS:
$.ajax({
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
if (self.file.size < self.max_length) {
var percent = Math.round((e.loaded / e.total) * 100);
} else {
var percent = Math.round((uploadedChunk / self.file.size) * 100);
}
$('.progress-bar').css('width', percent + '%')
$('.progress-bar').text(percent + '%')
}
});
return xhr;
},
url: '/create-post',
type: 'POST',
dataType: 'json',
cache: false,
processData: false,
contentType: false,
data: formData,
error: function (xhr) {
alert(xhr.statusText);
},
success: function (res) {
if (nextChunk < self.file.size) {
// upload file in chunks
existingPath = res.existingPath
self.upload_file(nextChunk, existingPath);
} else {
// upload complete
$('.textbox').text(res.data);
alert(res.data)
}
}
});
}};
Views:
https://imgur.com/a/FThSXAO
All of this gives me
parsererror
Nothing else...

How to prevent function from running if data error is returned

I have an AJAX request which shows a modal window with a progress bar when the data is computable but if there is an error I would like the error to be returned and the modal window to stay hidden.
$(document).ready(function(){
$(function () {
var pleaseWait = $('#pleaseWaitDialog');
showPleaseWait = function () {
pleaseWait.modal('show');
};
hidePleaseWait = function () {
pleaseWait.modal('hide');
};
});
var $myForm = $('.form')
$myForm.on('submit', function(event){
event.preventDefault();
var form = $(event.target)
var formData = new FormData(form[4]);
$.ajax({
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
showPleaseWait(); // <--------------- This runs even when view returns error
console.log('Percentage uploaded: ' + (e.loaded / e.total))
var percent = Math.round(e.loaded / e.total * 100);
$('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%');
}
});
return xhr;
},
type: 'POST',
url: form.attr('action'),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this),
success: function(data){
if (data.success) {
window.location.href = data.url;
}
if (data.error) {
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
}
},
});
});
});
I have tried moving the showPleaseWait function under the if(data.error) statement but this doesn't work.
How do I keep the modal window hidden if the response is (data.error)?
EDIT:
And this removes the HTML of the page and shows the JSON response instead:
success: function(data){
if (data.success) {
window.location.href = data.url;
}
error: function (jqXHR, exception) {
if (data.error) {
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
}
}
},
Your function is the "succes" property of the ajax object.
As shown in the doc, there is a "error" property to handle ajax error, here is the signature :
error(xhr,status,error)
Use it like you do with the succes property :
$.ajax({
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
showPleaseWait(); // <--------------- This runs even when view returns error
console.log('Percentage uploaded: ' + (e.loaded / e.total))
var percent = Math.round(e.loaded / e.total * 100);
$('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%');
}
});
return xhr;
},
type: 'POST',
url: form.attr('action'),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this),
success: function(data){
if (data.success) {
window.location.href = data.url;
}
},
error: function(xhr,status,error){
// Do something
}
});
I hope it solved your issue !
$.ajax() doc
I think you are using Jquery 3.0
so try this
var jqxhr = $.ajax({
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
showPleaseWait(); // <--------------- This runs even when view returns error
console.log('Percentage uploaded: ' + (e.loaded / e.total))
var percent = Math.round(e.loaded / e.total * 100);
$('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%');
}
});
return xhr;
},
type: 'POST',
url: form.attr('action'),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this),
success: function(data){
if (data.success) {
window.location.href = data.url;
}
if (data.error) {
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
}
},
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});

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');

Ajax progress not working properly

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");
});

Categories