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);
Related
I have a webpage with a few JavaScript functions set to load on document.ready.
However, if I have 4 of these, only the final one seems to load.
Here is the code I have.
$(document).ready(function ()
{
var nation = "ireland";
var irelandMatches = [];
var matchOrderReversed = false;
loadDoc();
showRSS("Irish Times");
loadWeather();
loadTwitter();
The loadDoc() and loadTwitter() methods load, but weather and showRSS do not. If I comment out loadTwitter(), then the weather loads fine.
If it makes any difference, all of these methods make use of an XMLHttpRequest, each of which is defined within each method, like so.
function loadYouTube()
{
var html = "";
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)
{
var ret = xmlhttp.responseText;
var spl1 = ret.split("~");
for (i = 0; i <= 10; i++)
{
var spl2 = spl1[i].split("*");
var current = "<a href='" + spl2[1] + "'><img src='" + spl2[2] + "' width='50' height='50'>" + "<a href='" + spl2[1] + "'>" + spl2[0] + "</a> <br/>";
html += current;
}
$("#yt").html(html);
}
}
xmlhttp.open("GET", "getyoutube.php?", true);
xmlhttp.send();
}
Thanks guys :)
It looks like when you define xmlhttp in your loadYouTube() example, you are doing so on the global scope due to the lack of var. So loadDoc() sets window.xmlhttp, then loadWeather() overwrites it shortly after, followed by loadTwitter().
Try something like this in your loading functions:
function loadYouTube()
{
var html = "";
// define xmlhttp in block scope
var xmlhttp;
// rest of function...
}
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);
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...
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>
I have a script i have been battling with now for like a week.
I have a page which has a div with id ("content"). Now I loaded some content, a form contained in a div tag to be specific, into this div VIA Ajax, and it is displaying fine
Now, the challenge is - When the form is submitted, Im am calling a function that will disable all the field on the element in that div tag. I always get the error "undefined".
It seems that the div, that i brought in to the page isn't recognized by javascript..
I have searched google, bing, yahoo..i just havent found the solution yet...
Please, what do I do??
I have included the code below --
+++++++++
The code below for my external javascript file
++++++++++++++++++++
// JavaScript Document
var doc = document;
var tDiv;
var xmlHttp;
var pgTitle;
function getXMLObj(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
Obj = new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
Obj = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support Ajax!");
}
return Obj;
}
function loadCont(toLoad, view){
doc.getElementById('loadBlank').innerHTML = '<div id="loading">Processing Request...</div>';
var url;
switch(toLoad){
case 'CI':
pgTitle = "Administration - Company Information";
url = "comp_info.php?v=" + view + "&sid=" + Math.random();
break;
case 'JB':
pgTitle = "Administration - Jobs";
url = "jobs.php?v=" + view + "&sid=" + Math.random();
break;
case 'US':
pgTitle = "Administration - Users";
url = "users.php?v=" + view + "&sid=" + Math.random();
break;
case 'EP':
pgTitle = "Administration - Employees";
url = "emp.php?v=" + view + "&sid=" + Math.random();
break;
case 'AP':
pgTitle = "Administration - Recruitments";
url = "applicants.php?v=" + view + "&sid=" + Math.random();
break;
case 'JV':
pgTitle = "Administration - Recruitments";
url = "jobvacancy.php?v=" + view + "&sid=" + Math.random();
break;
}
xmlHttp = getXMLObj();
if (xmlHttp !== null && xmlHttp !== undefined){
xmlHttp.onreadystatechange = loadingContent;
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}
}
function loadingContent(){
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
//Show the loading and the title, but hide the content...
if (xmlHttp.status == 200){
doc.getElementById('dMainContent').innerHTML = parseScript(xmlHttp.responseText);
doc.getElementById('loadBlank').innerHTML = '';
}
else{
doc.getElementById('dMainContent').innerHTML = 'Sorry..Page not available at this time. <br />Please try again later';
doc.getElementById('loadBlank').innerHTML = '';
}
}
if (xmlHttp.readyState < 4){
//Show the loading and the title, but hide the content...
doc.getElementById('ActTitle').innerHTML = pgTitle;
doc.getElementById('dMainContent').innerHTML = '';
}
}
function valCompInfo(){
//First Disable All the elements..
alert('I was hree');
DisEnaAll('CompForm');
//Now..lets validate the entries..
}
function DisEnaAll(contId){
//alert(doc.getElementById(contId).elements);
var theId = doc.getElementById(contId).elements;
try{
var numElems = theId.length;
for (var i=0; i < (numElems - 1); i++){
(theId[i].disabled == false) ? (theId[i].disabled = true) : (theId[i].disabled = false);
}
}
catch(e){
var msg = "The following error occurred: \n\n";
msg += e.description
alert(msg);
}
}
// http://www.webdeveloper.com/forum/showthread.php?t=138830
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}
This code is on the main page where the javascript is
<div id="dMainContent">
</div>
</body>
</html>
And finally, the content of the page i am loading via ajax..
<div style="width:738px" id="CompForm">
<div class="tdright">
<?php echo $btnNm; ?>
</div>
</div>
That's the code..
Thanks
The issue is with div tag (id "CompForm") which is not a HTML form.
"elements" is a collection of the form element not div element. So when trying to access div.elements the property is undefined.
See MSDN, form.elements is part of DOM level 1 (according to MSDN)
http://msdn.microsoft.com/en-us/library/ms537449%28v=VS.85%29.aspx
Add your Javascript functions or external JS file to the original page.
this is not JavaScript....
doc.getElementById(contId).elements
but is used in your JavaScript... you will definitely not get anything. (null)
I don't think this is valid either:
theId[i].disabled == false
EDIT: Note per comments: this is NOT the answer :) See comments for details of why.
Left as an answer simply as a learning aid aid as suggested.
Shouldn't
xmlHttp.onreadystatechange = loadingContent;
be
xmlHttp.onreadystatechange = loadingContent();
or
loadingContent();
and that function should return a value if you want to assign it like that...