cascading drop down with XML, javascript having problems - javascript

Here is my code. I am trying to create a cascading DropDown box in html with javascript and XML, and I am almost close to the end, but I just can't get this to work, can someone close this for me?
my script
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<EMPLOYEES xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
<DEPARTMENT>Operations</DEPARTMENT>
<DESIGNATION>Assistant Manager</DESIGNATION>
<NAME>Abhijit Khamkar</NAME>
<SUPERVISOR>Vamsee Nidiganti</SUPERVISOR>
<CTC>5541601.5100909</CTC>
</RECORD>
<RECORD>
<DEPARTMENT>Operations</DEPARTMENT>
<DESIGNATION>Team Leader</DESIGNATION>
<NAME>Elish Anand</NAME>
<SUPERVISOR>Abhijit Khamkar</SUPERVISOR>
<CTC>4356182.71368286</CTC>
</RECORD>
</EMPLOYEES>
My HTML
<html>
<head>
<meta charset="utf-8"/>
<title>Attendance Drop Down</title>
</head>
<body>
<div id="update" ></div>
<script>
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET','Employee.xml')
request.onreadystatechange = function() {
if((request.readyState===4) &&
(request.status===200)) {
var items = request.responseXML.getElementsByTagName('DEPARTMENT');
var output = '<select id="departments" onchange="update();">';
for (var i = 0; i < items.length; i++) {
output += '<option>' +
items[i].firstChild.nodeValue +'</option>';
}
output += '</select>';
document.getElementById('update').innerHTML = output;
}
}
function update(){
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET','Employee.xml')
request.onreadystatechange = function() {
if((request.readyState===4) &&
(request.status===200)) {
var items = request.responseXML.getElementsByTagName('DESIGNATION');
var output = '<select id="designations">';
for (var i = 0; i < items.length; i++) {
output += '<option>' +
items[i].firstChild.nodeValue +'</option>';
}
output += '</select>';
document.getElementById('update').innerHTML = output;
}
}
}
request.send();
</script>
</body>
</html>

You need to add:
request.send();
Inside your update function, the one you have is outside and used to do the initial call but won't get called when your update function is invoked.
<html>
<head>
<meta charset="utf-8"/>
<title>Attendance Drop Down</title>
</head>
<body>
<div id="update" ></div>
<script>
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET','Employee.xml')
request.onreadystatechange = function() {
if((request.readyState===4) &&
(request.status===200)) {
var items = request.responseXML.getElementsByTagName('DEPARTMENT');
var output = '<select id="departments" onchange="update();">';
for (var i = 0; i < items.length; i++) {
output += '<option>' +
items[i].firstChild.nodeValue +'</option>';
}
output += '</select>';
document.getElementById('update').innerHTML = output;
}
}
request.send();
function update(){
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET','Employee.xml')
request.onreadystatechange = function() {
if((request.readyState===4) &&
(request.status===200)) {
var items = request.responseXML.getElementsByTagName('DESIGNATION');
var output = '<select id="designations">';
for (var i = 0; i < items.length; i++) {
output += '<option>' +
items[i].firstChild.nodeValue +'</option>';
}
output += '</select>';
document.getElementById('update').innerHTML = output;
}
}
request.send();
}
</script>
</body>

Related

Javascript and json pharse loop with external file

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)

Parse big JSON Data info HTML Table

I want to implement the JSON File into an HTML Table. In my case it doesnt work however. The table should show all data at once (if possible)
<!DOCTYPE html>
<html>
<body>
<h2>Make a table based on JSON data.</h2>
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "name", limit: 50 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("GET", "http://infoportal.vag.de/InfoPortal/busstations.xhr", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send("x=" + dbParam);
</script>
</body>
</html>
this code should work (but not within this snippet)
const
Limit = 20,
LoadingTable = document.getElementById('Loading-Table')
;
let xdr = getXDomainRequest("get", "http://infoportal.vag.de/InfoPortal/busstations.xhr");
if (!xdr) {
throw new Error("no cross-domain allowed by your browser :/");
};
xdr.onload = function() {
jsonData = JSON.parse(xdr.responseText);
let line = 0;
for (elm in jsonData) {
let
row = LoadingTable.insertRow(line),
c_0 = row.insertCell(0),
c_1 = row.insertCell(1),
c_2 = row.insertCell(2),
c_3 = row.insertCell(3)
;
c_0.textContent = elm;
c_1.textContent = jsonData[elm].name;
c_2.textContent = jsonData[elm].x;
c_3.textContent = jsonData[elm].y;
if (++line >= Limit) break;
}
}
xdr.send();
function getXDomainRequest( method, url ) {
var xdr = null;
if (window.XDomainRequest) { // MS ie
xdr = new XDomainRequest();
xhr.open(method, url);
}
else if (window.XMLHttpRequest) {
xdr = new XMLHttpRequest();
if ('withCredentials' in xdr) {
xdr.open(method, url, true);
}
else {
xdr = null;
}
}
return xdr;
}
body {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
}
#Loading-Table {
border-collapse: collapse;
}
#Loading-Table,
#Loading-Table td {
border: 1px solid grey;
}
#Loading-Table td {
padding: 2px 10px;
}
<h2>Make a table based on JSON data.</h2>
<p id="demo"></p>
<table id="Loading-Table" ></table>

JavaScript - Calling an 'onClick' function from a For loop loading multiple links

I am in the process of creating a listview from JSON data however, after calling an 'onclick' function from a For loop, the link, which opens up in a new window, loads three URLs into the URL input of the browser. Any idea how I could re-work the below code to just load one link rather that the three based on the below code?
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
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++) {
URL_1 += arr[i].timetable_1_link;
URL_2 += arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can start by refactoring the function that opens the URL to accept a parameter like this:
function openLinkInNewWindow_1(URL) {
window.open(URL, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
Then in the for loop pass the URL along with each link.
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
This way you only need the one function. Notice also that I removed the + from the URL_1 += line.
Using URL_1+= is culprit here. Every time loops run it appends new string to existing url(s).
So remove += from URL_ variables in your function 'myFunction' and assign values directly by using '=' only.
Updated code is written below
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
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++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can take a look for updated and running code here

Get JSON data from a file using (JavaScript)

I need to know how can I get json data using JavaScript without using Jquery. I just want to know how to get data only using JavaScript.
My Json file.
{"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_default_view":3,"_deviceID":1,"_deviceName":"MobiTech","_deviceTypeID":1,"_projectID":1,"_roomID":2,"_roomName":"Room2","_room_admin_mail":null}]}
My home.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get Json</title>
</head>
<body>
<h1>My Home Page</h1>
<div id="results">
<!-- Display Jason Data -->
</div>
<script>
var resultDiv = document.getElementById("results");
var newsURL = "http://localhost:81/testjs/data.json";
var e;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
e = new XMLHttpRequest();
} else {
// code for IE6, IE5
e = new ActiveXObject("Microsoft.XMLHTTP");
}
e.onreadystatechange = function() {
var html = " ";
if (e.readyState == 4 && e.status == 200) {
response = JSON.parse(e.responseText);
if(typeof(e.responseText)==="string") {
d = e.responseText;
} else {
if (typeof(e.responseXML)==="object") {
d = e.responseXML;
};
}
var myData = response['JsonProjectIDResult'];
//Print results
html = myData[0]._capacity+"<br />";
html += myData[0]._description+"<br />";
html += myData[0]._dev_default_view+"<br />";
html += myData[0]._deviceID+"<br />";
html += myData[0]._deviceName+"<br />";
html += myData[0]._deviceTypeID+"<br />";
html += myData[0]._projectID+"<br />";
html += myData[0]._roomID+"<br />";
html += myData[0]._roomName+"<br />";
html += myData[0]._room_admin_mail+"<br />";
resultDiv.innerHTML = html;
}
};
e.open("GET", newsURL, true);
e.send();
</script>
</body>
</html>
After my friends gave me some helpful answer I wondered my code like this. It's working. Now I need to run this as a loop. When every records display using a loop. Can I do it in JavaScript.
<script>
var resultDiv = document.getElementById("results");
var newsURL = "http://localhost:81/testjs/data.json";
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.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
response = JSON.parse(xmlhttp.responseText);
//here you can manipulate the response as you wish, for example you can:
var myData = response['JsonProjectIDResult'];
// myData now is an array of the json object
var html = '<ul>';
for(var prop in myData ) {
if(myData.hasOwnProperty(prop))
html += '<li>' + prop + ' = ' + myData[prop] + '</li>';
}
html += '</ul>';
//and so on
resultDiv.innerHTML = html;
}
}
xmlhttp.open("GET", newsURL, true);
xmlhttp.send();
</script>

How do I read XML in JavaScript?

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.

Categories