Get JSON data from a file using (JavaScript) - 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>

Related

How to fetch child node values from xml file using javascript

I can fetch the <name> tag value from the XML below, but I can't fetch all of the <image><url> values:
<?xml version='1.0' encoding='ISO-8859-1'?>
<gallery>
<name>abc</name>
<email><![CDATA[smith#email.com]]></email>
<images>
<image>
<url><![CDATA[g2pic3.jpg]]></url>
<caption><![CDATA[Red Sun]]></caption>
</image>
<image>
<url><![CDATA[g2pic4.jpg]]></url>
<caption><![CDATA[Eiffel Tower]]></caption>
</image>
</images>
</gallery>
Here is my javascript code. I want to fetch all of the values included in
the <images> tag, but am having trouble with this part.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
}
xhttp.open("GET", "template.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
nameList = xmlDoc.getElementsByTagName("name");
var nameList = nameList[0].childNodes;
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}
//xmlDoc.getElementsByTagName("gallery").item(0).firstChild.nodeValue;
</script>
</body>
</html>
Pretty sure there are much better solutions to this. My plain old js is a little rusty.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
}
xhttp.open("GET", "template.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
// Create a object gallery to store the values.
var gallery = {};
gallery.name = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
gallery.email = xmlDoc.getElementsByTagName("email")[0].childNodes[0].nodeValue;
// Put all image elements into xmlImages
var xmlImages = xmlDoc.getElementsByTagName("image");
// Add an empty array to gallery
gallery.image = [];
// Iterate over all images in xmlImages
for(var i = 0; i < xmlImages.length; i++) {
var xmlImage = xmlImages[i];
// Create an new object and add url and caption values to it
var image = {};
image.url = xmlImage.getElementsByTagName("url")[0].childNodes[0].nodeValue;
image.caption = xmlImage.getElementsByTagName("caption")[0].childNodes[0].nodeValue;
// Add the image object to the gallery.image array
gallery.image.push(image);
}
// Quick and dirty, create a string with html tag to present the result
var html = "name: " + gallery.name + "<br>" +
"email: " + gallery.email + "<br>" +
"images:<br><ul>";
for(var i = 0; i < gallery.image.length; i++) {
html += "<li>image" + i + ":<br>";
html += "<ul><li>url: " + gallery.image[i].url + "</li>";
html += "<li>caption: " + gallery.image[i].caption + "</li></ul>";
}
html += "</ul>";
document.getElementById("demo").innerHTML = html;
}
</script>
</body>
</html>

Output XMLHttpRequest to DIV via javascript

I am trying to list out the station names of the local transit system via an API call in pure JS. I want to loop through the station names(45 of them) and output them into a list inside of div id="stationDiv"
All I am getting is a list of 45 empty object Elements listed inside the div. I can't seem to get the loop to output correctly.
Sample of XML file
<root>
<uri>
<![CDATA[ http://api.bart.gov/api/stn.aspx?cmd=stns ]]>
</uri>
<stations>
<station>
<name>12th St. Oakland City Center</name>
<abbr>12TH</abbr>
<gtfs_latitude>37.803664</gtfs_latitude>
<gtfs_longitude>-122.271604</gtfs_longitude>
<address>1245 Broadway</address>
<city>Oakland</city>
<county>alameda</county>
<state>CA</state>
<zipcode>94612</zipcode>
</station>
//44 more station's below this
Set up calling the API:
var URL ="http://api.bart.gov/api/stn.aspx?cmd=stns&key=MW9S-E7SL-26DU-VV8V"; //public key used
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",URL,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
if(xmlhttp.status == 200) {
console.log("connection successful");
} else {
console.log("server returned a status code of " + oHttp.status);
}
loop that is not working:
var x1=xmlDoc.getElementsByTagName("station");
function postNames(station) {
var x = station.length;
var n = 0;
var element = document.getElementById('stationDiv');
var html = '<ul>';
while(n < x) {
html += '<li>' + station[n] + '</li>';
n++;
}
html += '</ul>';
element.innerHTML = html;
}
postNames(x1);
Thank you in advance, I have multiple books and 20 tabs open in front of me but just can't seem to get it to output correctly.
PURE JS only please.
Try this...
var x1=xmlDoc.getElementsByTagName("station");
var postNames = function(station) {
var x = station.length;
var n = 0;
var element = document.getElementById('stationDiv');
var html = '<ul>';
while(n < x) {
html += '<li>' + station[n].getElementsByTagName("name")[0].childNodes[0].nodeValue + '</li>';
n++;
}
html += '</ul>';
element.innerHTML = html;
}
postNames(x1);

How to print xmlhttp response?

I am getting some information from database, this information is getting back into JSON format now I need to print this JSON information. But my code is not working getCountryDetails.php is php file for interacting with the database. Following code is the script, When I click the button It intersects with database.
<script type="text/javascript">
$(document).ready(function() {
$("#quickSearch").click(function(){
var countries = [];
$.each($("#select-choice-1 option:selected"), function(){
countries.push($(this).val());
});
if (countries == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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) {
//myFunction(xmlhttp.responseText);
myFunction(xmlhttp.responseText);
}
}
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET","webservices/getCountryDetails.php?q="+countries,true);
xmlhttp.send();
}
});
});
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
Firstly, countries will never be an empty string, you've defined it as an array
var countries = [];
...
if (countries == "") { // always fail
secondly, you can't concantenate an array into a string, and XMLHttpRequest doesn't accept arrays
xmlhttp.open("GET","webservices/getCountryDetails.php?q=" + countries, true);
Thirdly, you seem to be using jQuery, so why not use it as it does accept an array
$.ajax({
url : 'webservices/getCountryDetails.php',
data : countries
}).done(myFunction);

Generate Table dynamically with AJAX data using Javascript

I'm trying to dynamically generate a table with JavaScript using AJAX and displayed using Bootstrap but I can't seem to get the table to show.It only shows the header fields. Any help would be greatly appreciated.
<button onclick="display();">Generate Table</button>
<div id="myTable"></div>
function display(){
var HTML = "<table class='table table-striped table-bordered table-hover' style='width:500px'>";
HTML += "<tr><th>Place</th><th>Description</th></tr>";
var search = 106;
makeRequest('findplace.php?searchbynumber='+search,function(data){
var data = JSON.parse(data.responseText);
for(var i = 0;i<data.length;i++){
HTML += "<tr><td>" + data[i].place + "</td><td>" + data[i].description + "</td></tr>";
}
});
HTML += "</table>";
document.getElementById('myTable').innerHTML = HTML;
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
As Tim says in the comment, this is to do with the asynchronous nature of the call you're making in makeRequest.
You essentially build the outside of the table and add that the HTML, then the callback is called later, builds up a new variable and never does anything with it.
You have a number of options, but the simplest is probably to move the creation of the HTML into the callback and build it in one go on return from the onreadychangestate and you have everything you need to output.
I.E. Move ALL the HTML construction into your callback and the problem should go away:
function display(){
var search = 106;
makeRequest('findplace.php?searchbynumber='+search,function(data){
var HTML = "<table class='table table-striped table-bordered table-hover' style='width:500px'>";
HTML += "<tr><th>Place</th><th>Description</th></tr>";
var data = JSON.parse(data.responseText);
for(var i = 0;i<data.length;i++){
HTML += "<tr><td>" + data[i].place + "</td><td>" + data[i].description + "</td></tr>";
}
HTML += "</table>";
document.getElementById('myTable').innerHTML = HTML;
});
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
As for other options:
As one idea, you could build the outside of the table as you do, but with a "Loading..." bit of text in there and then add the rows in the callback - but if you're looking for that I'd say that's an exercise for the reader...

cascading drop down with XML, javascript having problems

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>

Categories