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