Ajax upload without progres bar - javascript

I have a some code to ajax upload . its send request to my servlet and all works fine. But code contains a progress bar what i no need. Can u help me delete lines what i no need?
Another question how to refresh DIV with my content after upload files? When i use this code to send parametrs to jsp page
$.post(
"deletePoly.jsp",
{ids:ch.toString()},
function(per){
$("#WRAPlist").load("listing.jsp");
}
);
Where i gonn put line
$("#WRAPlist").load("listing.jsp");
this is upload code
var req;
function ajaxFunction()
{
var url = "Upload_Servlet";
if (window.XMLHttpRequest) // Non-IE browsers
{
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject) // IE Browsers
{
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = processStateChange;
req.open("GET", url, true);
req.send();
}
}
}
function processStateChange()
{
* State Description
* 0 The request is not initialized
* 1 The request has been set up
* 2 The request has been sent
* 3 The request is in process
* 4 The request is complete
if (req.readyState == 4)
{
if (req.status == 200) // OK response
{
var xml = req.responseXML;
// No need to iterate since there will only be one set of lines
var isNotFinished = xml.getElementsByTagName("finished")[0];
var myBytesRead = xml.getElementsByTagName("bytes_read")[0];
var myContentLength = xml.getElementsByTagName("content_length")[0];
var myPercent = xml.getElementsByTagName("percent_complete")[0];
// Check to see if it's even started yet
if ((isNotFinished == null) && (myPercent == null))
{
document.getElementById("initializing").style.visibility = "visible";
// Sleep then call the function again
window.setTimeout("ajaxFunction();", 100);
}
else
{
document.getElementById("initializing").style.visibility = "hidden";
document.getElementById("progressBarTable").style.visibility = "visible";
document.getElementById("percentCompleteTable").style.visibility = "visible";
document.getElementById("bytesRead").style.visibility = "visible";
myBytesRead = myBytesRead.firstChild.data;
myContentLength = myContentLength.firstChild.data;
if (myPercent != null) // It's started, get the status of the upload
{
myPercent = myPercent.firstChild.data;
document.getElementById("progressBar").style.width = myPercent + "%";
document.getElementById("bytesRead").innerHTML = myBytesRead + " of " +
myContentLength + " bytes read";
document.getElementById("percentComplete").innerHTML = myPercent + "%";
// Sleep then call the function again
window.setTimeout("ajaxFunction();", 100);
}
else
{
document.getElementById("bytesRead").style.visibility = "hidden";
document.getElementById("progressBar").style.width = "100%";
document.getElementById("percentComplete").innerHTML = "Done!";
}
}
}
else
{
alert(req.statusText);
}
}
}

remove these line of codes then it will not display progressbar..
document.getElementById("initializing").style.visibility = "hidden";
document.getElementById("progressBarTable").style.visibility = "visible";
document.getElementById("percentCompleteTable").style.visibility = "visible";
document.getElementById("bytesRead").style.visibility = "visible";
myBytesRead = myBytesRead.firstChild.data;
myContentLength = myContentLength.firstChild.data;
if (myPercent != null) // It's started, get the status of the upload
{
myPercent = myPercent.firstChild.data;
document.getElementById("progressBar").style.width = myPercent + "%";
document.getElementById("bytesRead").innerHTML = myBytesRead + " of " +
myContentLength + " bytes read";
document.getElementById("percentComplete").innerHTML = myPercent + "%";
// Sleep then call the function again
window.setTimeout("ajaxFunction();", 100);
}
else
{
document.getElementById("bytesRead").style.visibility = "hidden";
document.getElementById("progressBar").style.width = "100%";
document.getElementById("percentComplete").innerHTML = "Done!";
}

Related

How to make Image load faster in my javascript code

I have a simple weather map where each time there is different weather status the background image should change the code below works fine but it takes seconds two change the image. so my question is, is this because of the way my code is structured, if not then what could be the issue and how can I improve the performance faster.
form.addEventListener("submit", getData);
function getData(e){
e.preventDefault();
const link = 'http://api.openweathermap.org/data/2.5/weather?q=';
const cityInput = input.value;
const apiId = '&appid=12345667889&units=metric';
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = ()=>{
if (xhr.readyState == 4 && xhr.status == 200) {
const object = JSON.parse(xhr.response);
country.textContent = object.sys.country;
city.textContent = cityInput;
humid.textContent = object.main.humidity + "%";
temp.textContent = object.main.temp;
wind.textContent = object.wind.speed + "mph";
let snrise = object.sys.sunrise;
let snset = object.sys.sunset;
let dtrise = new Date(snrise*1000);
let dtset = new Date(snset*1000);
let risehrs = dtrise.getHours();
let sethrs = dtset.getHours();
let risemnts = "0" + dtrise.getMinutes();
let setmnts = "0" + dtset.getMinutes();
sunrise.textContent = risehrs + ' : ' + risemnts.substr(-2) ;
sunset.textContent = sethrs + ' : ' + setmnts.substr(-2);
const weatherName = object.weather[0].description.slice(0,17);
status.textContent = weatherName;
if(weatherName.includes("rain")){
bgImg.src = "./images/rain.jpg";
}
else if(weatherName.includes("clouds")){
bgImg.src = "./images/clouds.jpg";
}
else if(weatherName.includes("snow")){
bgImg.src = "./images/snow.jpg";
}
else if(weatherName === "mist"){
bgImg.src = "./images/mist.jpg";
}
else if(weatherName === "clear sky"){
bgImg.src = "./images/clear-sky.jpg";
}
else if(weatherName === "smoke"){
bgImg.src = "./images/smoke.jpg";
}
else if(weatherName === "dust"){
bgImg.src = "./images/dust.jpg";
}
else if(weatherName === "drizzle"){
bgImg.src = "./images/rain.jpg";
}
else if(weatherName === "haze"){
bgImg.src = "./images/haze.jpg";
}
else if(weatherName === "fog"){
bgImg.src = "./images/foggy.jpg";
}
else if(weatherName === "thunderstorm"){
bgImg.src = "./images/thunderstorm.jpg";
}
else{
bgImg.src = "./images/pexels-photo-39811.jpg";
}
}
}
xhr.open('GET', link + cityInput + apiId, true);
xhr.send();
}
As soon you do bgImg.src the browser will lookup for that image, from cache (which is fast) - or from the internet - which causes the slow gap.
Instead, make sure the image is loaded, than set the bgImg.src to the loaded resource.
const icon = "";
if(weatherName.includes("rain")){
icon = "./images/rain.jpg";
} else if(weatherName.includes("clouds")){
icon = "./images/clouds.jpg";
} // etc...
const img = new Image();
img.addEventListener('load', () => bgImg.src = img.src );
img.src = icon;

How to add Node.js result in my HTML project?

this is my project: http://cryptotipsitalia.sytes.net/.
I want add Ethereum value down to "Valore BTC" with Node.js: https://www.npmjs.com/package/crypto-price.
How can I add it?
That's my code:
function getValueBTC() { <!-- chiamata API --> /
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
var output;
console.log(url);
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
output = this.responseText;
var obj = JSON.parse(output);
var rightValue = (obj.bpi.EUR.rate).substring(0,obj.bpi.EUR.rate.length-2); /* eliminazione ultime due cifre */
document.getElementById("cellaValoreBTC").innerHTML= obj.bpi.EUR.symbol + " " + rightValue;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-type", "text/plain");
xmlhttp.send();
}
let price = require('crypto-price');
price.getCryptoPrice('EUR', 'ETH').then(obj => {
console.log(obj.price); // It will print ETH rate per BTC
document.getElementById("cellaValoreETH").innerHTML = obj.price;
}).catch(err => {
console.log(err);
});
table><tr><td width="75%">VALORE BTC:</td></tr><tr id="cellaValoreBTC" width="75%"></tr><tr><td width="75%">VALORE ETH:</td></tr><tr id="cellaValoreETH" width="75%"></table>
Why "document.getElementById("cellaValoreBTC").innerHTML = obj.price;" doesnt' work?
How can I add obj.price in my HTML code?
Thanks

JS search returned xhr.responseText for div then remove div

I would like to search a xhr.responseText for a div with an id like "something" and then remove all the content from the xhr.responseText contained within that div.
Here is my xhr code:
function getSource(source) {
var url = source[0];
var date = source[1];
/****DEALS WITH CORS****/
var cors_api_host = 'cors-anywhere.herokuapp.com';
var cors_api_url = 'https://' + cors_api_host + '/';
var slice = [].slice;
var origin = self.location.protocol + '//' + self.location.host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
var args = slice.call(arguments);
var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
targetOrigin[1] !== cors_api_host) {
args[1] = cors_api_url + args[1];
}
return open.apply(this, args);
};
/****END DEALS WITH CORS****/
var xhr = new XMLHttpRequest();
xhr.open("GET", cors_api_url+url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = xhr.responseText;
var respWithoutDiv = removeErroneousData(resp);
}
else{
return "Failed to remove data.";
}
}
xhr.send();
}
remove div here:
/*This must be in JS not JQUERY, its in a web worker*/
function removeErroneousData(resp) {
var removedDivResp = "";
/*pseudo code for removing div*/
if (resp.contains(div with id disclosures){
removedDivResp = resp.removeData(div, 'disclosures');
}
return removedDivResp;
}
You can dump the response in a div and then search for that div you want empty its content.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = xhr.responseText;
$('div').attr('id', 'resp').html(resp);
$('#resp').find('disclosures').html('');
//var respWithoutDiv = removeErroneousData(resp);
}
else{
return "Failed to remove data.";
}
}

XMLHttpRequest don't send to another page

I use this code to upload files, and this code have a progressbar. The problem with this code is that it never send me to "upload.php" after it have uploaded the file, after it reach 100% on the progressbar. (It's not my code).
The code:
// get form data for POSTing
//var vFD = document.getElementById('upload_form').getFormData(); // for FF3
var vFD = new FormData(document.getElementById('upload_form'));
// create XMLHttpRequest object, adding few event listeners, and POSTing our data
var oXHR = new XMLHttpRequest();
oXHR.upload.addEventListener('progress', uploadProgress, false);
oXHR.addEventListener('load', uploadFinish, false);
oXHR.addEventListener('error', uploadError, false);
oXHR.addEventListener('abort', uploadAbort, false);
oXHR.open('POST', 'upload.php');
oXHR.send(vFD);
The whole script
// common variables
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
var iMaxFilesize = 1048576; // 1MB
var oTimer = 0;
var sResultFileSize = '';
var uploadingcanceld = "حدث خطأ أثناء تحميل الملف";
function secondsToTime(secs) { // we will use this function to convert seconds in normal time format
var hr = Math.floor(secs / 3600);
var min = Math.floor((secs - (hr * 3600))/60);
var sec = Math.floor(secs - (hr * 3600) - (min * 60));
if (hr < 10) {hr = "0" + hr; }
if (min < 10) {min = "0" + min;}
if (sec < 10) {sec = "0" + sec;}
if (hr) {hr = "00";}
return hr + ':' + min + ':' + sec;
};
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
function fileSelected() {
// hide different warnings
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
// get selected file element
var oFile = document.getElementById('ufile').files[0];
// filter for image files
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! rFilter.test(oFile.type)) {
document.getElementById('error').style.display = 'block';
return;
}
// little test for filesize
if (oFile.size > iMaxFilesize) {
document.getElementById('warnsize').style.display = 'block';
return;
}
// get preview element
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function(e){
// e.target.result contains the DataURL which we will use as a source of the image
oImage.src = e.target.result;
oImage.onload = function () { // binding onload event
// we are going to display some custom image information here
sResultFileSize = bytesToSize(oFile.size);
document.getElementById('fileinfo').style.display = 'block';
document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
};
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
function startUploading() {
// cleanup all temp states
iPreviousBytesLoaded = 0;
$("#upload").animate({height:'75px'},350);
$("#loadingborders").fadeIn(1500);
$("#progress_percent").fadeIn(1500);
$("#upload_button").fadeOut(100);
$("#ufile").fadeOut(100);
document.getElementById('ufile').style.margin = '5px 0px -5px 0px';
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
document.getElementById('progress_percent').innerHTML = '';
var oProgress = document.getElementById('progress');
oProgress.style.display = 'block';
oProgress.style.width = '0px';
// get form data for POSTing
//var vFD = document.getElementById('upload_form').getFormData(); // for FF3
var vFD = new FormData(document.getElementById('upload_form'));
// create XMLHttpRequest object, adding few event listeners, and POSTing our data
var oXHR = new XMLHttpRequest();
oXHR.upload.addEventListener('progress', uploadProgress, false);
oXHR.addEventListener('load', uploadFinish, false);
oXHR.addEventListener('error', uploadError, false);
oXHR.addEventListener('abort', uploadAbort, false);
oXHR.open('POST', 'upload.php');
oXHR.send(vFD);
// set inner timer
oTimer = setInterval(doInnerUpdates, 300);
}
function doInnerUpdates() { // we will use this function to display upload speed
var iCB = iBytesUploaded;
var iDiff = iCB - iPreviousBytesLoaded;
// if nothing new loaded - exit
if (iDiff == 0)
return;
iPreviousBytesLoaded = iCB;
iDiff = iDiff * 2;
var iBytesRem = iBytesTotal - iPreviousBytesLoaded;
var secondsRemaining = iBytesRem / iDiff;
// update speed info
var iSpeed = iDiff.toString() + 'B/s';
if (iDiff > 1024 * 1024) {
iSpeed = (Math.round(iDiff * 100/(1024*1024))/100).toString() + 'MB/s';
} else if (iDiff > 1024) {
iSpeed = (Math.round(iDiff * 100/1024)/100).toString() + 'KB/s';
}
document.getElementById('speed').innerHTML = iSpeed;
document.getElementById('remaining').innerHTML = '| ' + secondsToTime(secondsRemaining);
}
function uploadProgress(e) { // upload process in progress
if (e.lengthComputable) {
iBytesUploaded = e.loaded;
iBytesTotal = e.total;
var iPercentComplete = Math.round(e.loaded * 100 / e.total);
var iBytesTransfered = bytesToSize(iBytesUploaded);
document.getElementById('progress_percent').innerHTML = iPercentComplete.toString() + '%';
document.getElementById('progress').style.width = (iPercentComplete * 4).toString() + 'px';
document.getElementById('b_transfered').innerHTML = iBytesTransfered;
if (iPercentComplete == 100) {
var oUploadResponse = document.getElementById('upload_response');
oUploadResponse.innerHTML = '<h1>Please wait...processing</h1>';
}
} else {
document.getElementById('progress').innerHTML = 'unable to compute';
}
}
function uploadFinish(e) { // upload successfully finished
var oUploadResponse = document.getElementById('upload_response');
oUploadResponse.innerHTML = e.target.responseText;
document.getElementById('progress_percent').innerHTML = '100%';
document.getElementById('progress').style.width = '400px';
document.getElementById('filesize').innerHTML = sResultFileSize;
document.getElementById('remaining').innerHTML = '| 00:00:00';
clearInterval(oTimer);
}
function uploadError(e) { // upload error
$('#errormessage').slideUp('fast', function() {
$('#errormessage').html(uploadingcanceld);
$('#errormessage').slideDown('fast');
});
clearInterval(oTimer);
}
function uploadAbort(e) { // upload abort
clearInterval(oTimer);
}
XHR is a dynamic data call, it's not a document forwarding call, meaning the reason why we have XHR to begin with is so that we DON'T want to forward a client to another page to get new content into the page. So you might want to wait on the XHR to complete the process of sending the data, acquire the results of that transfer via XHR, and based on those results do as you want.
So in essence, you are creating a virtual document client/server transfer and handshake without having to forward the client, that of which is the role XHR was created to fulfill.

Content Insensitive Autosave via XMLHttpRequest

I am trying to make an autosave that can be dropped into any of my forms and be "self aware" of the content in order to simulate an actual save. In addition, I want it to be able to notify the user in the event of multiple failures of the autosave. The following is the come I have come up with, but I keep getting readyState = 4 and status = 500 as a result of my XMLHttpRequest.send(). When I "normally" click save with the form, the save works perfectly fine, but this code just doesn't seem to pass the data over correctly. Every page that has this code has a setTimeout(autosave,5000) to initialize the code. Can someone point me in the right direction of what I'm doing wrong? I'm new to XMLHttpRequest objects.
For what I can tell, last_params gets "sent" with the correct data, but when I get it via the request() (using classic ASP on the other end), the value is "" (blank). I'm thinking I have an order of execution problem, I just don't know what or where.
Quick footnote: I know that there are 'similar' functions with jQuery and other frameworks, but I do not feel comfortable enough with them yet. I want to start with something "simple".
var last_params = "";
var autosave_time = 61000;
var autosave_fail_check = 5;
var max_autosave_fail_check = 5;
var response_text = "";
function autosave() {
var autosave_button_name = "save_button";
var form_action = document.getElementById("formS").action;
var form_data = document.getElementById("formS");
var all_inputs = form_data.getElementsByTagName("input");
var all_textareas = form_data.getElementsByTagName("textarea");
var params = "";
// Check all inputs for data
for (var i = 0; i < all_inputs.length; i++) {
var current_item = all_inputs[i];
if (current_item.type != "button" && current_item.type != "submit") {
if (current_item.type != "checkbox") {
params += current_item.name + "=" + current_item.value + "&";
} else {
params += current_item.name + "=" + current_item.checked + "&";
}
}
}
// check all textareas for data
for (var i = 0; i < all_textareas.length; i++) {
var current_item = all_textareas[i];
params += current_item.name + "=" + current_item.value + "&";
}
params += "autosave=1";
if (params == last_params) {
setTimeout(autosave, autosave_time);
return;
} else {
last_params = params;
}
// Setup time
var time = "";
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
time = hours + ":" + minutes + ":" + seconds;
if(hours > 11){
time = time + "PM";
} else {
time = time + "AM";
}
var status = "[]";
// **************************************************
var http;
try {
// Gecko-based browsers, Safari, and Opera.
http = new XMLHttpRequest();
} catch(e) {
try {
// For Internet Explorer.
http = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
// Browser supports Javascript but not XMLHttpRequest.
document.getElementById(autosave_button_name).value = "Autosave NOT Available";
http = false;
}
}
http.onreadystatechange = function()
{
if (http.readyState == 4 && http.status == 200) {
autosave_fail_check = max_autosave_fail_check; // reset the fail check
}
status = " [" + http.readyState + " / " + http.status + "] ";
}
if (autosave_fail_check <= 0) {
if (autosave_fail_check == 0) {
document.getElementById(autosave_button_name).value = "Autosave FAILURE; Check Connection!";
//alert("Autosave has FAILED! Please check your connection!");
}
autosave_fail_check = -1;
} else {
autosave_fail_check--;
}
var url = form_action;
http.open("POST", url, true); // async set to false to prevent moving on without saving
http.setRequestHeader("Content-type", "multipart/form-data");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(last_params);
response_text = http.responseText;
if (autosave_fail_check >= 0) {
document.getElementById(autosave_button_name).value = "Last Saved: " + time + " [" + autosave_fail_check + "] " + status;
} else {
autosave_fail_check = -1;
}
setTimeout(autosave, autosave_time);
} // end function autosave()

Categories