Progress bar of some files do not load (javascript) - javascript

this is my problem.
I have an input to upload several files at the same time, then I have an ajax that is responsible for sending the request and events listener to load the bars.
The problem is when I upload 8 files and some do not meet the validations (size and format), then draw most of the bars and the last ones do not.
The file is uploaded but neither the bar nor the text is drawn
This is the javascript code
<script type="text/javascript">
var newFileList = [];
$('.addfiles').on('click', function () { $('#fileUploader').click(); return false; });
$(document).ready(function () {
$('input[type=file]').change(function () {
if (this.files.length != 0) { $("#btnUpload").attr('disabled', false); };
$("#bars").remove();
$("#divFiles").append('<div id="bars"></div>')
for (var i = 0; i < this.files.length; i++) { //Progress bar and status label's for each file genarate dynamically
var fileId = i;
const file = this.files[i];
if (validateFileExtension(file)) {
$("#bars").append(
'<div id = "' + fileId + '" >' +
'<div>' + file.name + '</div>' +
'<div class="progress">' +
'<div class="bar" id="progressbar_' + fileId + '" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>' +
' </div>' +
'<div>' +
'<input type="button" class="btn btn-danger" style="display:none;line-height:6px;height:25px" id="cancel_' + fileId + '" value="cancel">' +
'</div>' +
'<div>' +
'<p class="progress-status" style="text-align: right;margin-right:-15px;font-weight:bold;color:saddlebrown" id="status_' + fileId + '"></p>' +
'</div>' +
'<div>' +
'<p id="notify_' + fileId + '" style="text-align: right;"></p>' +
'</div>' +
'</div>'
);
}
};
$('file_count').text('# Files selected: ' + newFileList.length);
})
});
function uploadFiles() {
var file = document.getElementById("fileUploader")//All files
for (var i = 0; i < newFileList.length; i++) {
uploadSingleFile(newFileList[i], i);
}
}
function uploadSingleFile(file, i) {
var fileId = i;
var ajax = new XMLHttpRequest();
//Progress Listener
ajax.upload.addEventListener("progress", function (e) {
console.log(file);
var percent = (e.loaded / e.total) * 100;
$("#status_" + fileId).text(Math.round(percent) + "% uploaded, please wait...");
$('#progressbar_' + fileId).css("width", percent + "%")
$("#notify_" + fileId).text("Uploaded " + (e.loaded) + " KB of " + (e.total) + " KB ");
}, false);
//Load Listener
ajax.addEventListener("load", function (e) {
$("#status_" + fileId).text("File upload!");
$('#progressbar_' + fileId).css("width", "100%")
//Hide cancel button
var _cancel = $('#cancel_' + fileId);
_cancel.hide();
}, false);
//Error Listener
ajax.addEventListener("error", function (e) {
$("#status_" + fileId).text("Upload Failed");
}, false);
//Abort Listener
ajax.addEventListener("abort", function (e) {
$("#status_" + fileId).text("Upload Aborted");
}, false);
var imagePath = window.location.search;
var filePath = imagePath.replace("imagePath", "filePath");
ajax.open("POST", "/File"+filePath); // Your API .net, php
var uploaderForm = new FormData(); // Create new FormData
uploaderForm.append("file", file); // append the next file for upload
ajax.send(uploaderForm);
//Cancel button
var _cancel = $('#cancel_' + fileId);
_cancel.show();
_cancel.on('click', function () {
ajax.abort();
})
}
function validateFileExtension(file) {
if (!/(\.bmp|\.jpg|\.gif|\.png)$/i.test(file.name)) {
bootbox.alert("Invalid file type:" + file.name + " . Only JPG, GIF, PNG or BMP File");
return false;
}
// Validate Size
var imgsize = document.getElementById('ImgSize').value;
var size = file.size;
// check file size
if (size > imgsize) {
$(this).val("");
bootbox.alert("The size of " + file.name + " is too big: " + size + " Byte, you only can upload " + imgsize + " Byte");
return false;
}
newFileList.push(file);
return true;
}
</script>
EDIT
apply the changes but follow the same problem the file is uploaded, but the bar is not drawn on the screen or anything else
function uploadFiles() {
filesToUpload = newFileList.slice(0);
uploadSingleFile(filesToUpload.pop(), 0); // start the process here
}
function uploadSingleFile(file, i) {
var fileId = i;
var ajax = new XMLHttpRequest();
//Progress Listener
ajax.upload.addEventListener("progress", function (e) {
var percent = (e.loaded / e.total) * 100;
$("#status_" + fileId).text(Math.round(percent) + "% uploaded, please wait...");
$('#progressbar_' + fileId).css("width", percent + "%")
$("#notify_" + fileId).text("Uploaded " + (e.loaded) + " KB of " + (e.total) + " KB ");
}, false);
//Load Listener
ajax.addEventListener("load", function (e) {
$("#status_" + fileId).text("File upload!");
$('#progressbar_' + fileId).css("width", "100%")
//Hide cancel button
var _cancel = $('#cancel_' + fileId);
_cancel.hide();
}, false);
//Error Listener
ajax.addEventListener("error", function (e) {
$("#status_" + fileId).text("Upload Failed");
}, false);
//Abort Listener
ajax.addEventListener("abort", function (e) {
$("#status_" + fileId).text("Upload Aborted");
}, false);
var imagePath = window.location.search;
var filePath = imagePath.replace("imagePath", "filePath");
ajax.open("POST", "/File" + filePath); // Your API .net, php
var uploaderForm = new FormData(); // Create new FormData
uploaderForm.append("file", file); // append the next file for upload
ajax.send(uploaderForm);
ajax.onreadystatechange = function () {
if (ajax.readyState === 4) {
if (ajax.status === 200) {
console.log('successful');
if (filesToUpload.length > 0) { // do this inside your ajax success call
uploadSingleFile(filesToUpload.pop(), ++i);
}
else {
console.log(ajax.status);
console.log('failed');
}
}
}
}
//Cancel button
var _cancel = $('#cancel_' + fileId);
_cancel.show();
_cancel.on('click', function () {
ajax.abort();
})
}

Related

Twitch TV API JSON Issue

I work with Twitch API. If the streamer streams I work with with property "Stream". But If he's not streaming, then I need refer to another link. Then I again turn to the function of the getJSON and pass there the necessary API link. And I'm working with her. However, the loop does not work as it should. It takes the last streamer out of the "channels" array, but it should all those who do not stream. I can not understand what the problem is. Help...
JSFiddle: https://jsfiddle.net/e7gLL25y/
JS Code:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == "200") {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send();
};
var channels = ["summit1g", "esl_RuHub_CSGO", "Starladder1", "Senpai_Frozen", "tehvivalazz", "ESL_CSGO"];
var client_id = "hx3dea4ifwensxffoe8iwvekwvksnx";
var section = document.getElementById("main-section");
var streamer = [];
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
getJSON(url_streams, function(response) {
if( response["stream"] !== null ) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + response.stream.channel["url"] +
"'><img id='streamer-image' src='" +
response.stream.channel["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
response.stream.channel["name"] +
"</h2><p id='stream-status'>" +
response.stream["game"] + "</p></a>";
section.appendChild(streamer[i]);
} else {
getJSON(url_channels, function(r) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + r["url"] +
"'><img id='streamer-image' src='" +
r["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
r["name"] +
"</h2><p id='stream-status'>Offline</p></a>";
section.appendChild(streamer[i]);
});
}
});
}
You are having a common misconception about JavaScript contexts.
Refer to my answer here to see details about this problem: https://stackoverflow.com/a/42283571/1525495
Simply, the getJSON response is called after all the array is looped, so i will be the last index in all the responses. You have to create another context to keep the i number so is not increased.
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
(function(i) {
// i will not be changed by the external loop as is in another context
getJSON(url_streams, function(response) {
// Thingy things...
});
})(i);
}

Uncaught TypeError: subir_file.forEach is not a function

I have a problem with the conversion object to array..
In the next code read a file json and input de information in a div byte_content
This part of code it's ok..
function leer_json() {
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
subir_file = evt.target.result;
alert(subir_file);
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);
}
The second function capture the var subir_file and try the read with the
each but the problem its of diferent type the date..
function sube_json() {
var table = document.getElementById('d_t_json');
subir_file.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.Tipo + '</td>' +
'<td>' + object.Idenfificacion + '</td>' +
'<td>' + object.Periodo_inicial + '</td>' +
'<td>' + object.Periodo_final + '</td>';
table.appendChild(tr);
});
}
please .. how I can change the code .. I need charge the json into talbe of html ..

Formdata and XMLhttpRequest not Working on IE 11

I am using formdata and XMLHttpRequest to submit my form using ajax. Now everything works well on other browsers except IE 11 . Note I am uploading a file using this ajax request.
My code is as follows
var form = document.getElementById('chatMessageForm');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.responseType = "json";
xhr.send(formData);
xhr.onload = function (e) {
var new_message_response = xhr.response; // not responseText
console.log(new_message_response);
if (new_message_response.conversationStatus) {
alert('This Conversation is disabled by Other User');
jQuery('.conversationadd .messagebox #msgbox').attr('disabled',true);
} else {
var downloadLink = '';
if (new_message_response.attachment != '' && new_message_response.attachment != null) {
downloadLink = 'Download Attachment';
}
jQuery('.chatmessageinner').append('<div class="singlemsg right" id=" ' + new_message_response.id + ' ">'
+ '<p> ' + msg + ' </p>'
+ '<div class="messagefooter">'
+ '<span class="time">' + new_message_response.time + '</span>'
+ downloadLink
+ '</div>'
+ '</div>');
var objDiv = document.getElementsByClassName("chatmessageinner")["0"];
objDiv.scrollTop = objDiv.scrollHeight;
}
}
I have used jQuery.ajax instead of XMLhttpRequest now everything works smooth as silk :) Now my code looks like this:
var form = document.getElementById('chatMessageForm');
var formData = new FormData(form);
jQuery.ajax({
url: form.getAttribute('action'),
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
var new_message_response = data;
if (new_message_response.conversationStatus)
{
alert('This Conversation is disabled by Other User');
jQuery('.conversationadd .messagebox #msgbox').attr('disabled', true);
}
else
{
var downloadLink = '';
if (new_message_response.attachment != '' && new_message_response.attachment != null)
{
downloadLink = 'Download Attachment';
}
jQuery('.chatmessageinner').append('<div class="singlemsg right" id=" ' + new_message_response.id + ' ">'
+ '<p> ' + msg + ' </p>'
+ '<div class="messagefooter">'
+ '<span class="time">' + new_message_response.time + '</span>'
+ downloadLink
+ '</div>'
+ '</div>');
var objDiv = document.getElementsByClassName("chatmessageinner")["0"];
objDiv.scrollTop = objDiv.scrollHeight;
}
},
error: function (data) {
alert("error");
}
});

How to debug page loading errors in phantomJs

Is there a way to debug page.open method of phantomjs ? My application loads some files saved locally but unfortunately the only info one can get when opening the page is if it was loaded successfully or not. What more interesting the very same page loads properly when opened in the browser.
Here's my code :
var system = require('system'),
page = require('webpage').create();
var openPage = function () {
var url = 'http:\\localhost:53794/file.html';
page.open(url, function (status) {
if (status !== 'success') {
console.log("FAIL:" + url);
phantom.exit(2);
}
var date = new Date().getTime();
var outputFilename = outputPath + 'print-' + date + '.png';
setTimeout(function () {
page.render(outputFilename);
outputArray.push(outputFilename);
setTimeout(function () {
phantom.exit(1);
}, 1);
}, 1);
});
}
openPage();
via: http://newspaint.wordpress.com/2013/04/25/getting-to-the-bottom-of-why-a-phantomjs-page-load-fails/
After creating the page variable, but before calling page.open() add the following code:
page.onResourceError = function(resourceError) {
page.reason = resourceError.errorString;
page.reason_url = resourceError.url;
};
Now you can print out the reason for a problem in your page.open() callback, e.g.:
var page = require('webpage').create();
page.onResourceError = function(resourceError) {
page.reason = resourceError.errorString;
page.reason_url = resourceError.url;
};
page.open(
"http://www.nosuchdomain/",
function (status) {
if ( status !== 'success' ) {
console.log(
"Error opening url \"" + page.reason_url
+ "\": " + page.reason
);
phantom.exit( 1 );
} else {
console.log( "Successful page open!" );
phantom.exit( 0 );
}
}
);
Debugging Function
If you read further down the blog, he has some more suggested event handlers to add. I adapted them into a function that you can use to inject the event handlers into your page object (instead of having them defined in your main code)
// this method injects some debugging event handlers
// into a PhantomJS page object.
// usage:
// var page = require('webpage').create();
// var system = require('system');
// addDebugEvents(page,system);
function addDebugEvents(page, system) {
page.onResourceError = function (resourceError) {
page.reason = resourceError.errorString;
page.reason_url = resourceError.url;
};
page.onResourceRequested = function (request) {
system.stderr.writeLine('= onResourceRequested()');
system.stderr.writeLine(' request: ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function (response) {
system.stderr.writeLine('= onResourceReceived()');
system.stderr.writeLine(' id: ' + response.id + ', stage: "' + response.stage + '", response: ' + JSON.stringify(response));
};
page.onLoadStarted = function () {
system.stderr.writeLine('= onLoadStarted()');
var currentUrl = page.evaluate(function () {
return window.location.href;
});
system.stderr.writeLine(' leaving url: ' + currentUrl);
};
page.onLoadFinished = function (status) {
system.stderr.writeLine('= onLoadFinished()');
system.stderr.writeLine(' status: ' + status);
};
page.onNavigationRequested = function (url, type, willNavigate, main) {
system.stderr.writeLine('= onNavigationRequested');
system.stderr.writeLine(' destination_url: ' + url);
system.stderr.writeLine(' type (cause): ' + type);
system.stderr.writeLine(' will navigate: ' + willNavigate);
system.stderr.writeLine(' from page\'s main frame: ' + main);
};
page.onResourceError = function (resourceError) {
system.stderr.writeLine('= onResourceError()');
system.stderr.writeLine(' - unable to load url: "' + resourceError.url + '"');
system.stderr.writeLine(' - error code: ' + resourceError.errorCode + ', description: ' + resourceError.errorString);
};
page.onError = function (msg, trace) {
system.stderr.writeLine('= onError()');
var msgStack = [' ERROR: ' + msg];
if (trace) {
msgStack.push(' TRACE:');
trace.forEach(function (t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
system.stderr.writeLine(msgStack.join('\n'));
};
}
You should change the URL
from
http:\\localhost:53794/file.html
to
http://localhost:53794/file.html

Extension stopped working with Google Chrome manifest v2

I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.

Categories