Alright, so I got this xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<level>
<tiles>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1111111111111111</row>
</tiles>
</level>
and I got my XML reading code:
var xmlDoc = document.implementation.createDocument("","",null);
and
function loadXML(){
xmlDoc.load("levels/test.xml");
xmlDoc.onload = readLevel();
}
function readLevel() {
throw(xmlDoc);
if(xmlDoc.getElementsByTagName("tiles")[0].hasChildNodes()){
var rowNum = xmlDoc.getElementsByTagName("tiles").getChildNodes();
level = [];
for(var i = 0; i < rowNum; i++){
level[i] = [];
var tempStr = xmlDoc.getElementsByTagName("tiles").childNodes[i].textContent;
for(var j = 0; j < 16; j++){
level[i][j] = parceInt(tempStr.charAt(j));
}
}
}
for (var i = 0; i < level.length; i++) {
blockArray[i] = []; // Create the second level for this index
for (var j = 0; j < level[i].length; j++) {
var tempImg = new Image();
tempImg.src = "images/block" + level[i][j] + ".png";
blockArray[i][j] = new block(j * blockSize, i * blockSize, level[i][j], false, false, tempImg);
//throw('blockArray['+i+']'+j+'] = ' + level[i][j]);
}
}
}
Now why isn't this working? It constantly says xmlDoc.getElementsByTagName("tiles")[0] is undefined and that xmlDoc.getElementsByTagName("tiles").length = 0. So what am I doing wrong?
I'd use XMLHttpRequest and its responseXML property instead, which will work in all major browsers. Example:
function readLevel(xmlDoc) {
alert(xmlDoc.documentElement.tagName);
// Your existing code goes here
};
var createXmlHttpRequest = (function() {
var factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
for (var i = 0, len = factories.length; i < len; ++i) {
try {
if ( factories[i]() ) return factories[i];
} catch (e) {}
}
})();
var xmlHttp = createXmlHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
readLevel(xmlHttp.responseXML);
}
};
xmlHttp.open("GET", "levels/test.xml", true);
xmlHttp.send(null);
According to SitePoint, all the arguments are required in createDocument. Maybe the falsy values are tripping you up.
Related
I should loop this json file to javascript, all the entries are important and must be retrieved.
I need to make this json compatible with this javascript code.
This is my json file:
{ "user_token":"6664e310e87f75ad4fd5674a976f8310", "lesson_language":"it_de", "language_app":"it", "main_levels":[ { "level":"1_it_de" }, { "level":"5_it_de" } ] }
This is my code javascript:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
var user_token = arr[0].user_token;
for(i = 0; i < arr.length; i++) {
var level = arr[i].level;
out += user_token;
}
document.getElementById("id01").innerHTML = out;
}
var jsonInput={ "user_token":"6664e310e87f75ad4fd5674a976f8310", "lesson_language":"it_de", "language_app":"it", "main_levels":[ { "level":"1_it_de" }, { "level":"5_it_de" } ] }
function myFunction(arr) {
var out = "";
var i;
var userLabel=''
var user_token = arr.user_token;
mainArrObj=arr.main_levels
for(i = 0; i < mainArrObj.length; i++) {
var level = mainArrObj[i].level;
out += user_token + ' ';
userLabel += level + ' ';
}
console.log('user_token :'+out);
console.log('userLabel :'+userLabel);
}
myFunction(jsonInput)
How can I loop my json file using my script, eg: I should choose whether to loop Schema A or Schema B.
My json file is:
{
"A":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
],
"B":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
]
}
Maybe setting a variable so as to define the scheme I have to display
My javascript file is:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj= JSON.parse(this.responseText);
myFunction(obj, 'A');
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj, key) {
var arr = obj[key];
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
Assuming that what you presented as JSON file is a response form network and is passed to myFunction, then why not to do something like:
let myRootArray;
if(/* some confitions */) {
myRootArray = myArr.A
} else {
myRootArray = myArr.B
}
myFunction(myRootArray );
Beside that, your names are a bit confusing, var myArr = JSON.parse(this.responseText);, while JSON.parse will return object, not an array.
I want to get a file from client side to parse it into json object and send it to the backend, i am able to parse the file thanks to Sheet-js.
My problem is i can not get files from client side
I am using js, SAPUI5
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
if (!oFileUploader.getValue().toString()) {
MessageToast.show("Choose a xlsx file first");
return;
}
var url = "/resources/test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = [];
for (var i = 0; i !== data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {
type: "binary"
});
var firstSheetName = workbook.SheetNames[0];
var worksheet = workbook.Sheets[firstSheetName];
var json = XLSX.utils.sheet_to_json(worksheet, {
raw: true
});
var jsonStr = JSON.stringify(json);
MessageBox.show("JSON String: " + jsonStr);
};
oReq.send();
},
The answer is:
UploadFile.view.xml
<VBox>
<u:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
<Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
UploadFile.controller.js
handleTypeMissmatch: function(oEvent) {
var aFileTypes = oEvent.getSource().getFileType();
jQuery.each(aFileTypes, function(key, value) {
aFileTypes[key] = "*." + value;
});
var sSupportedFileTypes = aFileTypes.join(", ");
MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
" is not supported. Choose one of the following types: " +
sSupportedFileTypes);
},
handleValueChange: function(oEvent) {
MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
},
handleFileSize: function(oEvent) {
MessageToast.show("The file size should not exceed 10 MB.");
},
handleFileNameLength: function(oEvent) {
MessageToast.show("The file name should be less than that.");
},
onUpload: function(e) {
var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "EmployeesJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
var Len = data.length;
data.reverse();
params += "[";
for (var j = 0; j < Len; j++) {
params += JSON.stringify(data.pop()) + ", ";
}
params = params.substring(0, params.length - 2);
params += "]";
// MessageBox.show(params);
var http = new XMLHttpRequest();
var url = oResourceBundle.getText("UploadEmployeesFile").toString();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
var json = JSON.parse(http.responseText);
var status = json.status.toString();
switch (status) {
case "Success":
MessageToast.show("Data is uploaded succesfully.");
break;
default:
MessageToast.show("Data was not uploaded.");
}
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
};
reader.readAsBinaryString(file);
}
I have this code, this it's my object:
var sendData = function(ob) {
var obj = ob;
return {
send: function() {
obj.myform.onsubmit = function(e) {
var file = obj.file.files;
var ajax = new XMLHttpRequest();
var formdata = new FormData();
for(var i = 0; i < file.length; i++) {
formdata.append(data[], file[i]);
}
ajax.upload.onprogress = function(event) {
oojs.byID('container').innerHTML = Math.round((event.loaded / event.total)*100)+"%";
}
ajax.onload = function() {
oojs.byID('container').innerHTML = "Done";
}
ajax.onerror = function() {
oojs.byID('container').innerHTML = "Error";
}
ajax.onabort = function() {
oojs.byID('container').innerHTML = "Abort";
}
ajax.open("POST", "result.php");
ajax.send(formdata);
e.preventDefault();
}
}
}
}
oojs.sendData = sendData;
I want for each file one progress bar but, now i have just one progrss bar,
for(var i = 0; i < file.length; i++) {
formdata.append(data[], file[i]);
}
In this loop each file is added to formdata, i want send formdata for each file especially. I'm allready try do like this:
for(var i = 0; i < file.length; i++) {
var formdata = new FormData();
formdata.append(data, file[i]);
// ...
ajax.send(formdata);
}
Could you please try something like this:
function sendFile (file, progressCallback) {
var ajax = new XMLHttpRequest();
var formdata = new FormData();
formdata.append(file.name, file);
ajax.upload.onprogress = function(event) {
progressCallback(Math.round((event.loaded / event.total)*100));
};
ajax.onload = function() {
oojs.byID('container').innerHTML = "Done";
};
ajax.onerror = function() {
oojs.byID('container').innerHTML = "Error";
};
ajax.onabort = function() {
oojs.byID('container').innerHTML = "Abort";
};
ajax.open("POST", "result.php");
ajax.send(formdata);
}
var progress = 0;
var filesLength = files.length;
for(var i = 0; i < filesLength; i++) {
sendFile(files[i], function (x) {
progress = progress + x;
oojs.byID('container').innerHTML = (Math.round((progress / filesLength))) + '%';
});
}
I have a submit button that submits the date/time period for Annotation Chart in Google Charts.
When I click the button, it redraws the chart with new query result.
It redraws the chart, but every time it does that, it also generates a trailing, empty container as in the screenshot below.
https://www.dropbox.com/s/7fyiy6pxlxkmeik/Screen%20Shot%202014-05-01%20at%2011.58.59%20AM.png
If you see the screenshot, you can see there is two chart_div2_AnnotationChart_containerTable.
I can't simply ignore this new containerTable or delete it, because it contains the buttons and annotations for the refreshed chart.
How can I fix this?
When I redraw the chart, I am calling the function below with new query result.
function drawChart(myData, id) {
var data = new google.visualization.DataTable();
var params = myData[0];
for(var i = 0; i < params.length; i++) {
data.addColumn(params[i][0], params[i][1]); //type and name pair
}
var q_result = myData[1];
var rows = new Array(q_result.length);
for(var i = 0; i < q_result.length; i++) {
tmp_array = [];
for(var j = 0; j < q_result[0].length; j++) {
var tobeadded = params[j][0]=='date'?
new Date(q_result[i][j]) : q_result[i][j];
tmp_array.push(tobeadded);
}
rows[i] = tmp_array;
}
data.addRows(rows);
var chart = new google.visualization.AnnotationChart(
document.getElementById('chart_div'+id));
var options = {
displayAnnotations: true,
};
chart.draw(data, options);
}
When the chart is redrawn, drawChart() is called in the function below.
function g(idx, start, end) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", '/${conf["name"]}/submit_data?idx=' + idx + '&start=' + start + '&end=' + end, true);
xmlhttp.onreadystatechange = function(i) {
return function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
drawChart(JSON.parse(xmlhttp.responseText), i);
}
};
}(idx);
xmlhttp.send();
}
When the chart is initially drawn, it is called from the function below.
function getData() {
// code for IE7+, Firefox, Chrome, Opera, Safari
xhrs = [];
if(window.XMLHttpRequest) {
for (var i = 0; i < ${size}; ++i) {
xhrs.push(new XMLHttpRequest());
}
}
else { // code for IE6, IE5
for (var i = 0; i < ${size}; ++i) {
xhrs.push(new ActiveXObject("Microsoft.XMLHTTP"));
}
}
for (var i = 0; i < ${size}; ++i) {
xhrs[i].open("GET", '/${conf["name"]}/submit_data?idx=' + i, true);
xhrs[i].onreadystatechange = function(idx) {
return function() {
if(xhrs[idx].readyState == 4 && xhrs[idx].status == 200) {
drawChart(JSON.parse(xhrs[idx].responseText), idx);
}
};
}(i);
xhrs[i].send();
}
}
Here's some example code that reuses chart objects instead of recreating them:
function drawCharts () {
var data = [], charts = [], xhrs = [], options = {
displayAnnotations: true
};
for (var i = 0; i < ${size}; ++i) {
if(window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xhrs.push(new XMLHttpRequest());
}
else {
// code for IE6, IE5
// you probably want to throw an error here, since the visualization API does not support IE 5, 6 anyway
xhrs.push(new ActiveXObject("Microsoft.XMLHTTP"));
}
charts.push(new google.visualization.AnnotationChart(document.getElementById('chart_div'+id));
xhrs[i].open("GET", '/${conf["name"]}/submit_data?idx=' + i, true);
xhrs[i].onreadystatechange = function(idx) {
return function() {
if(xhrs[idx].readyState == 4 && xhrs[idx].status == 200) {
var myData = JSON.parse(xhrs[idx].responseText);
data[idx] = new google.visualization.DataTable();
var params = myData[0];
for(var i = 0; i < params.length; i++) {
data[idx].addColumn(params[i][0], params[i][1]); //type and name pair
}
var q_result = myData[1];
var rows = new Array(q_result.length);
for(var i = 0; i < q_result.length; i++) {
tmp_array = [];
for(var j = 0; j < q_result[0].length; j++) {
var tobeadded = params[j][0]=='date' ? new Date(q_result[i][j]) : q_result[i][j];
tmp_array.push(tobeadded);
}
rows[i] = tmp_array;
}
data[idx].addRows(rows);
charts[idx].draw(data[idx], options);
}
};
}(i);
xhrs[i].send();
}
}