How to wait for all XHR2 send calls to finish - javascript

I have done some code to upload multiple files from browser to server, while showing progressbars as well.
XHR2 send calls are asynchronous. The problem is that I want to call some functions after all the XHR2 send calls are finished.
Here is a very simplified snippet of my code:
<input id="upload" multiple="multiple" />
<script>
var files = document.getElementById("upload").files;
for (var i = 0, length = files.length; i < length; i++) {
var file = files[i];
var uploadFunc = function (arg) {
return function () {
processXHR(arg);
};
}(file);
uploadFunc();
}
function processXHR(file) {
var normalizedFileName = getNormalizedName(file.name);
var url = 'upload_file/';
var formData = new FormData();
formData.append("docfile", file);
var xhr = new XMLHttpRequest();
var eventSource = xhr.upload;
eventSource.addEventListener("progress", function (evt) {
var position = evt.position || evt.loaded;
var total = evt.totalSize || evt.total;
console.log('progress_' + normalizedFileName);
console.log(total + ":" + position);
$('#progress_' + normalizedFileName).css('width', (position * 100 / total).toString() + '%');
}, false);
eventSource.addEventListener("loadstart", function (evt) {
console.log('loadstart');
}, false);
eventSource.addEventListener("abort", function (evt) {
console.log('abort');
}, false);
eventSource.addEventListener("error", function (evt) {
console.log('error');
}, false);
eventSource.addEventListener("timeout", function (evt) {
console.log('timeout');
}, false);
xhr.onreadystatechange = function (evt) {
if (xhr.readyState == 4) {
console.log('onreadystatechange: File uploaded.');
}
};
xhr.open('post', url, true);
xhr.send(formData);
}
</script>
Whenever "onreadystatechange: File uploaded." is printed in console, I know that one of the files is done uploading.
But I am not able to write any code that will say "All Files uploaded.".
Thanks for any help.
I am using jquery as well in case some one has a solution using jquery.

Do you know how many calls you are making? If so, at least ajax callback, you check the count. Something like
if (ajaxCallCount === ajaxCallsLength) {
// Do stuff involving post all ajax calls
} else {
ajaxCallCount++;
}

You will need a counter and setInterval method in your case, try this:
<input id="upload" multiple="multiple" />
<script>
var files = document.getElementById("upload").files;
var counter = 0;
for (var i = 0, length = files.length; i < length; i++) {
var file = files[i];
var uploadFunc = function (arg) {
return function () {
processXHR(arg);
};
}(file);
uploadFunc();
}
var interval = setInterval(function() {
if(counter == files.length) {
clearInterval(interval);
console.log("All Files uploaded!");
}
}, 100);
function processXHR(file) {
var normalizedFileName = getNormalizedName(file.name);
var url = 'upload_file/';
var formData = new FormData();
formData.append("docfile", file);
var xhr = new XMLHttpRequest();
var eventSource = xhr.upload;
eventSource.addEventListener("progress", function (evt) {
var position = evt.position || evt.loaded;
var total = evt.totalSize || evt.total;
console.log('progress_' + normalizedFileName);
console.log(total + ":" + position);
$('#progress_' + normalizedFileName).css('width', (position * 100 / total).toString() + '%');
}, false);
eventSource.addEventListener("loadstart", function (evt) {
console.log('loadstart');
}, false);
eventSource.addEventListener("abort", function (evt) {
console.log('abort');
}, false);
eventSource.addEventListener("error", function (evt) {
console.log('error');
}, false);
eventSource.addEventListener("timeout", function (evt) {
console.log('timeout');
}, false);
xhr.onreadystatechange = function (evt) {
if (xhr.readyState == 4) {
counter += 1;
}
};
xhr.open('post', url, true);
xhr.send(formData);
}
</script>

Related

AJAX Error: POST http://localhost/upload/undefined 404 (Not Found)

I have been searching the net and testing for hours now but I could not pinpoint what the error is. So, I am looking for your kind help here. I followed step by step multiple files upload tutorial with the drag & drop functionality but I got the error message as mentioned in the title (and the line of code that throws the error is xmlhttp.send(data); ).
File upload.js has this function:
(function(o) {
"use strict";
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if (this.readyState === 4) {
if(this.status === 200){
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function'){
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1) {
data.append('files[]', source[i]);
}
return data;
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options.files));
}
};
}());
and the global.js file has this code:
(function() {
"use strict";
var dropZone = document.getElementById('drop-zone');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files) {
app.uploader({
files: files,
Processor: 'upload.php',
finished: function(data){
var x;
var uploadedElement;
var uploadedAnchor;
var uploadStatus;
for (x = 0; x < data.length; x = x + 1) {
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'uploaded-console-upload';
uploadedAnchor = document.getElementById('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded) {
uploadedAnchor.href = 'uploads/' + currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function() {
//console.log('There was an error');
}
});
};
//Standard form upload
document.getElementById('standard-upload').addEventListener('click', function(e) {
var standardUploadFiles = document.getElementById('standard-upload-files').files;
e.preventDefault();
startUpload();
});
//Drop funtionality
dropZone.ondrop = function(e){
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function() {
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function() {
this.className = 'upload-console-drop';
return false;
};
}());
Any help to solve this problem would be greatly appreciated. Thank you.
o.options.processor was defined as Processor and when it was called back later in the code, it was referred to as processor (changing from Processor to processor) solved the case. Thank you guys with your comments that helped me to find the error.

Nothings happens to the new element on page

I have following code, which highlights (fadein/out) the replied comment (its a div element).
I show only 10 last comments on the page
If the comment is found, then I highlight it (working fine), otherwise I load all comments and then try to highlight necessary one. But after loadAllComments function in the else clause the hide() method is not working - I wonder why.
function showReply(reply){
var p = getElement(reply);
if (p) {
$("#" + reply).animate({
opacity: 0.5
}, 200, function () {
});
setTimeout(function () {
$("#" + reply).animate({
opacity: 1
}, 200, function () {
});
}, 1000);
}
else{
loadAllComments(); //load all elements. working fine
$("#"+reply).hide(); //nothing happens. :-(
}
function loadAllComments() {
deleteComments();
$('.show-more-button').hide();
var xhr = new XMLHttpRequest();
xhr.open('GET', api_url + 'video_comments/?video=' + video_id, true);
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert(xhr.responseText);
}
else {
var comments = JSON.parse(xhr.responseText);
for (var i = comments.results.length - 1 ; i >= 0 ; i--){
$('.comment-content-box').append(showComment(comments.results[i]));
}
}
}
};
xhr.send();
}
function deleteComments(){
var comments_count = $('.comment-content-box').children('div').length;
for (var i=0; i < comments_count; i++){
$('.comment-render-box').remove();
}
}
function showComment(comment) {
return "<div>" // example, there is plenty of code, but it's just a return function
}
You're performing an XHR which is asynchronous. Supply a callback function to loadAllComments to be executed after your XHR completes:
function loadAllComments(callback) {
deleteComments();
$('.show-more-button').hide();
var xhr = new XMLHttpRequest();
xhr.open('GET', api_url + 'video_comments/?video=' + video_id, true);
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert(xhr.responseText);
}
else {
var comments = JSON.parse(xhr.responseText);
for (var i = comments.results.length - 1 ; i >= 0 ; i--){
$('.comment-content-box').append(showComment(comments.results[i]));
}
// xhr is complete and comments are now in DOM
callback();
}
}
};
xhr.send();
}
...
// usage
loadAllComments(function() {
$('#' + reply).hide();
});

Maintaining state of variables when changed inside a timer

I am using JavaScript.
I amusing a setInterval timer method.
Inside that method I am changing the values of module variables.
The thing is in IE the changes to the variables are not 'saved'. But in Chrome they are.
What is the accepted practice to do what I need to do?
this is my code:
function start()
{
var myVar = setInterval(function () { GetTimings() }, 100);
}
var currentts1;
var currentts2;
var currentts3;
var currentts4;
var frameCounter;
function GetTimings() {
if (frameCounter < 1) {
frameCounter++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", urlTS, false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var nextts = xmlhttp.responseText;
var bits = nextts.split('|');
if (currentts1 != bits[0]) {
currentts1 = bits[0];
postMessage("0|" + bits[0]);
}
if (currentts2 != bits[1]) {
currentts2 = bits[1];
postMessage("1|" + bits[1]);
}
if (currentts3 != bits[2]) {
currentts3 = bits[2];
postMessage("2|" + bits[2]);
}
if (currentts4 != bits[3]) {
currentts4 = bits[3];
postMessage("3|" + bits[3]);
}
frameCounter--;
}
}
xmlhttp.send();
}
}
The variables:
currentts1
currentts2
currentts3
currentts4
frameCounter
values are not preserved...
Try this, but notice I changed the currentts* to an Array when you try to view them
function start() {
var myVar = setInterval(GetTimings, 100);
}
var currentts = [null, null, null, null];
var in_progress = 0; // clear name
function GetTimings() {
var xhr;
if (in_progress > 0) return; // die
++in_progress;
xhr = new XMLHttpRequest();
xhr.open('GET', urlTS);
function ready() {
var nextts = this.responseText,
bits = nextts.split('|'),
i;
for (i = 0; i < currentts.length; ++i)
if (currentts[i] !== bits[i])
currentts[i] = bits[i], postMessage(i + '|' + bits[i]);
--in_progress;
}
if ('onload' in xhr) // modern browser
xhr.addEventListener('load', ready);
else // ancient browser
xhr.onreadystatechange = function () {
if (this.readyState === 4 && xhr.status === 200)
ready.call(this);
};
// listen for error, too?
// begin request
xhr.send();
}

XMLHttpRequest loop memory leak

I'm trying to check many items against information on ajax URL. But when I'm running this function in browser, memory usage goes above 2 gigs and then browser crashes (Chrome, Firefox). What am I doing wrong? items variable is really big - >200 000 and also includes some large strings.
var items = [1,2,3,4,5,6,7,8,9,10,...,300000]
var activeItems = {}
function loopAjax(){
for (i=0; i < items.length; i++) {
var currItem = items[i];
var request = new XMLHttpRequest();
var found = 0
request.open("GET", "/item=" + currItem);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var response = JSON.parse(request.responseText);
var active = response[0].active;
if (active) {
console.log("FOUND ACTIVE! " + currItem);
activeItems[found] = {"active": true, "item": currItem};
found++;
}
}
}
request.send();
}
}
Thank goodness the browser stalls and dies. If it didn't you just created a denial of service attack!
The problem needs to be reapproached. You better off creating a state machine which has a stack of requests in it. That way you only doing say 5 concurrent requests at a time.
function ItemChecker(sample_size, max_threads) {
this.sample_size = sample_size;
this.max_threads = max_threads;
this.counter = 0;
this.activeItems = [];
this.isRunning = false;
this.running_count = 0;
}
ItemChecker.prototype.start = function start() {
this.isRunning = true;
while (this.running_count < this.max_threads) {
this.next();
}
return this;
};
ItemChecker.prototype.stop = fucntion stop() {
this.isRunning = false;
return this;
};
ItemChecker.prototype.next = function next() {
var request, item_id, _this = this;
function xhrFinished(req) {
var response;
if (req.readyState !== 4) {
return;
}
_this.counter--;
if (req.status === 200) {
try {
response = JSON.parse(request.responseText);
if (response[0].active) {
_this.activeItems.push({
active: true,
item: item_id;
});
}
} catch(e) {
console.error(e);
}
// When finished call a callback
if (_this.onDone && _this.counter >= _this.sample_size) {
_this.onDone(_this.activeItems);
}
}
else {
console.warn("Server returned " + req.status);
}
}
if (!this.isRunning || this.counter >= this.sample_size) {
return;
}
item_id = this.counter;
this.counter++;
request = new XMLHttpRequest();
request.onreadystatechange = xhrFinished;
request.open("GET", "item=" + item_id);
request.send();
};
ItemChecker.prototype.whenDone = function whenDone(callback) {
this.onDone = callback;
return this;
};
This might work? Didn't try it for real. But you would call it with:
var item_checker = new ItemChecker(300000, 5);
item_checker.whenDone(function(active) {
// Do something with active
}).start();

Javascript variable reverting to original

function loadAll() {
var zip64;
var zipURL = 'settings/Images.zip';
var xhr = new XMLHttpRequest();
xhr.open('GET', zipURL, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
if (this.status == 200) {
var responseArray = new Uint8Array(this.response);
var d = responseArray.length;
var binaryString = new Array(d);
while (d--) {
binaryString[d] = String.fromCharCode(responseArray[d]);
}
var data = binaryString.join("");
zip64 = window.btoa(data);
zip.createReader(new zip.Data64URIReader(zip64), function(reader) {
reader.getEntries(function(entries) {
z = 0;
zloopid = setInterval(function() {
if (z >= entries.length || !entries[z]) {
clearInterval(zloopid);
reader.close();
start();
return;
}
if (entries[z].filename.split("/")[0] == "__MACOSX") {
z++;
return;
}
$("#loadimg").html("Loading " + entries[z].filename + ".... (" + (z + 1) + " of " + entries.length + ")");
var isMask = (entries[z].filename.replace(/^.*[\\\/]/, '') == "mask.jpg");
entries[z].getData(new zip.Data64URIWriter(), function(uri) {
if (isMask) {
imgtemp = new Image();
imgtemp.src = uri;
}
else {
var lol = new Image();
lol.src = uri;
imageLibrary.push(lol);
}
});
z++;
}, 0);
});
}, function(error) {
window.location = "error.html?err=Error by unzipper: " + error + " (Problem in Images.zip)";
});
}
else {
window.location = "error.html?err=Error while retrieving zip file (" + zipURL + ") : " + this.status;
}
};
xhr.send();
}
function start() {
var image = imgtemp;
width = image.width;
height = image.height;
So I have this piece of code. I have a global variable named imgtemp but everytime I set it in the if (inMask) block, it reverts to undefined when start() is called. Why is this?
loadAll() is called first, then start(). I can confirm that when the code that calls start() in loadAll() executes, imgtemp already turned back to undefined.
Thanks in advance!
It is because loadAll becomes async and returns before anything is loaded so when you call start the image has not been set yet. You'll need to "chain" them instead of calling them separately.
Only call loadAll() and then inside the loadAll add an event handler for loading the image which when loaded calls the start() function.
/* snip */
entries[z].getData(new zip.Data64URIWriter(), function(uri) {
if (isMask) {
imgtemp = new Image();
imgtemp.onload = function(event) {
start(); /* <--- HERE */
}
imgtemp.src = uri;
}
else {
/* snip */

Categories