jQuery, ajax .done fired late? - javascript

did anyone have an idea why the:
success, complete and done
event fired 5-10 seconds later than the "xhr.upload.addEventListener("load")" event?
What is the correct event?
iam not shure, which time the correct upload-time is?
hope, that somebody can help me :)
greets
paD
$('body').on('change', '#fileUploader', function() {
// Post-Daten vorbereiten
//var data = new FormData();
//data.append('file', this.files[0]);
var xhr = new XMLHttpRequest();
var data = new FormData();
var files = $("#fileUploader").get(0).files;
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
// Ajax-Call
$.ajax({
url: '<?=$this->language->modulLink('Upload/DoUpload');?>',
data: data,
type: 'POST',
cache: false,
processData: false,
contentType: false,
success: function() {
console.log("JETZT");
},
complete: function(){
console.log( "action finished" );
},
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete + ' :: ' + evt.loaded + ' :: ' + evt.total);
//Do something with upload progress here
}
}, false);
xhr.upload.addEventListener("load", function(evt) {
console.log("rdy");
}, false);
return xhr;
},
}).done(function(d) { console.log(d); });
});

It's because you are making AJAX call which is asynchronous. Ajax sends the Request from the client side and without waiting for the response starts executing the code statements written(in your case event listener) after the AJAX call code statement. Then once it receives the response from server, based on the response it executes either the success/failure method.
(1.) Ajax call is sent
-->
(2.) Statements after the AJAX call (i.e eventlistener method) are executed
-->
(3.) Server finally responds to AJAX call
-->
(4.) Success method of AJAX call is executed
I recommend you to go through this tutorials. AJAX

Related

Get status of form submission from backend

Is it possible to get status of each steps from backend? Like when I submit multipart form through ajax, it should show file upload progress, once it's finished it should show file format conversion progress then aws upload progress. Tried following ajax trick but it only show for upload progress.
$.ajax({
url: url,
type:"POST",
data: data,
processData: false,
contentType: false,
xhr: function(){
var xhr = $.ajaxSettings.xhr() ;
// set the onprogress event handler
xhr.upload.onprogress = function(evt){ console.log('progress', evt.loaded/evt.total*100) } ;
// set the onload event handler
xhr.upload.onload = function(){ console.log('DONE!') } ;
// return the customized object
return xhr ;
}
})
it's expressjs in backend. Please let me know if I'm doing it wrong or any suggestions.

jQuery's "uploadProgress" not firing in "$.ajax"

I am new to jQuery and now, I am currently working on file uploads. And I want to add some progress bar each time I upload image. I used the uploadProgress in jQuery but it seems doesn't work. Here's my code:
$('#_form_').on('submit', function(e){
var file_and_desc = new FormData($(this)[0]),
form_url = "_pages/_form_";
var ext = choose.val(),
allowed = ['jpg','png'];
if(ext){
var get_ext = ext.split('.');
get_ext.reverse();
if($.inArray(get_ext[0].toLowerCase(), allowed) > -1){
//upload image
$.ajax({
url : form_url,
type: 'POST',
data: file_and_desc,
contentType: false,
processData: false,
uploadProgress: function(event, positio, total, percentComplete){
$('h1').html(percentComplete);
},
success: function(data){
// some code here...
}
});
}
}
});
That's it! What should I do?
According to the $.ajax() reference, uploadProgress is not a valid option.
Instead, the xhr option is used instead, which lets you set progress listeners on the XMLHttpRequest that is used by the ajax request.
this answer shows how to do that:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
//Do something with upload progress here
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something on success
}
});

Avoid multiplication of ajax request

I have a little problem with my functions.
When I execute a function which launchs an Ajax call several times, each time, it multiplicate the number of call.
For example, I want to send a commentary, the first time, all is going good. But if I want to send another, it will be send twice. And if I do it again, it will be send three times.
If you can help me, it will be great :D
Thanks in advance.
Javascript:
$('.modifier').live('click',function(e){
e.preventDefault();
$('#error').hide();
var form = document.querySelector('form')
var formdata = new FormData(form);
formdata.append('fichier', window.file[0]);
//console.log(window.file[0]);
$('input[name=titre]').val('');
$('input[name=fichier]').val('');
$('textarea[name=description]').val('');
window.request_upload = $.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;
$('.chargement').show();
$('.chargement> #progress_bar').css({'width' : percentComplete*100 + '%'}).text(Math.round(percentComplete*100) + '%');
//console.log(percentComplete);
}
}, false);
return xhr;
},
url: "foobar.php",
type: "POST",
data: formdata,
async: true ,
cache: false,
contentType: false,
processData: false
})
.done(function(data){
var json = $.parseJSON(data);
//console.log('Data : '+data);
//console.log('L\'erreur : '+json.erreur);
if(json.erreur == 0)
{
//console.log(json.titre);
var titre = json.titre;
$.notify('Votre photo : "'+titre+'" a bien été envoyé !',{autoHideDelay: 10000, className: 'success'});
$('.drop_depot').removeClass('hover');
$('.chargement').hide();
$(this).removeClass('hover');
$('.drop_depot').empty().append('<span>'+options.message+'</span>');
$('.drop_depot').css({'width': '30%', 'height': '100px' });
$(window).resize();
$('input[type=file]').val('');
}
else{
$('.chargement').hide();
$('#error').show().after(json.erreur + ' ' + json.erreurs);
}
});
}
});
I load this script by : $.getScript() function. If it can help ...
I got the solution.
My problem come from the multiple execution of $.getScript() function.
But I could do this to solve it :
if(!$("body").data(script_bool))
{
$.getScript(script);
$("body").data(script_bool, true);
}
The script_bool variable is the name of the script called.
If it can help someone.

Implement SSE (Server Sent Events) with File Upload to ASHX Handler

I want to implement the following:
Call an ASHX hanlder from UI using Jquery.
Upload a file to this ASHX handler.
And when upload is complete, I want to keep sending messages from the server to UI (SSE) to tell the user about the execution status of the code in ASHX handler.
I am stuck with the 3rd point that has been mentioned above.
Following is the UI code that I have written:
var file = $("input#importFileInputHidden")[0].files[0];
var formData = new FormData();
formData.append('file', file);
importAjaxCall = $.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
$('#progressBar').show();
//Method to show the progress of the file being uploaded
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round((evt.loaded / evt.total) * 100);
$('#percentageImportComplete').text('' + percentComplete + '%');
$('#importStatus').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
type: 'post',
url: "Handler.ashx",
data: formData,
processData: false,
contentType: false,
success: function (data) {
//Some code to show success status to user
});
How to capture the messages I am sending from the server?
Have to tried to look into responseText property of http request?
success: function () {
console.log(xhr.responseText);
});

Ajax request monitoring flow

I have an AJAX Request in a JavaScript script where I GET a file like that:
$.ajax({
type: "GET",
url: "./" + img_type + ".bmp",
dataType: "html",
timeout: test_timeout,
cache: false,
success: function(msg)
{
//some stuff
}
});
The code itself is correct and works perfectly.
Is there a way to know HOW much of the file I've downloaded while the request is still ongoing?
I mean, once the request gives to me the success message I know that I've downloaded the entire file, but what if I want to know after two seconds of beginning?
Check out the "monitoring progress" section here:
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
Here's an example:
var xhr = new XMLHttpRequest;
xhr.onprogress = function(e){
if(e.lengthComputable){
var progress = e.position || e.loaded;
var total = e.totalSize || e.total;
var percent = progress/total*100;
//do something with progress here
}
};
xhr.onload = function(){
var content = xhr.responseText;
//do something with the result here
};
xhr.open('GET','./'+type+'.bmp',true);
xhr.send();

Categories