Why is this JavaScript code giving me error "undefined"? - javascript

I also tried using loadXML() of Microsoft, but it doesn't work. It is most likely deprecated. What perceives to be wrong here. Is there any other way to write it?
The HTML code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>childNode Property</title>
<script type="text/javascript" src="allfeaturetest.js"></script>
</head>
<body>
<h1>childNode Property</h1>
<hr/>
<form name="input">
<input type="button" value="Press me for XML" onclick="return xmlly()"/>
</form>
<div id="pop">
</div>
</body>
</html>
The JavaScript Code:
function xmlly(){
var resul ="";
var dom = new DOMParser();
var xmlDoc = dom.parseFromString("address.xml","application/xml");
var myElem = xmlDoc.getElementsByTagName("address").childNodes;
alert(myElem); //gives me undefined
alert(xmlDoc); //gives me [Object XMLDocument]
document.getElementById("pop").innerHTML = xmlDoc.documentElement.childNodes[0].attributes[0].nodeValue;
}
The XML file :
<address>
<street>Roble Ave</street>
<mtfcc>S1400</mtfcc>
<streetNumber>649</streetNumber>
<lat>37.45127</lat>
<lng>-122.18032</lng>
<distance>0.04</distance>
<postalcode>94025</postalcode>
<placename>Menlo Park</placename>
<adminCode2>081</adminCode2>
<adminName2>San Mateo</adminName2>
<adminCode1>CA</adminCode1>
<adminName1>California</adminName1>
<countryCode>US</countryCode>
</address>
The error shown to me:
Uncaught TypeError: Cannot read property 'nodeValue' of undefined

parseFromString will not load the data from the address.xml file. As the name says, it will only parse an XML doc from a string, like this:
var dom = new DOMParser();
var xmlDoc = dom.parseFromString("<address>test</address>","application/xml");
You'll need a separate XHR (Ajax) request to load the data from that file.
Also, you should be using console.log instead of an alert to debug this. You'll be able to actually see what's in that object (an error message in your case).

If your sole purpose is to read a node, use below functions -
function xmlly()
{
var xmlDoc=loadXMLDoc("address.xml");
var elm = xmlDoc.getElementsByTagName("street")[0]; // tag name you want to read
var node =elm.childNodes[0];
alert(node.nodeValue)
}
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}

Related

How to retrieve xml data using ajax

I am trying to retrieve data stored in XML file using JavaScript. But after clicking on button there is no response. Nothing happens after clicking on button. It is even not showing any error and no output. I am unable to understand what is wrong with following code. Please help.
<html>
<head>
<title>Requesting XML data in AJAX Student information</title>
<script language="JavaScript">
function getData()
{
var xhr;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xhr=new XMLHttpRequest();
//xhr.overrideMimeType("text/xml");
}
else
{
// code for IE6, IE5
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
var n=xhr.responseXML;
dispData(n);
}
}
xhr.open("GET","student.xml",true);
xhr.send();
}
function dispData(xmlDoc)
{
var a,f1,f2,f3,f4,disp;
//using javascript properties
a=xmlDoc.documentElement;
f1=a.firstChild;
f2=f1.nextSibling;
f3=f2.nextSibling;
f4=f3.nextSibling;
disp="<b>using javascript properties</b><br>";
disp=disp+"PRN:"+f1.firstChild.nodeValue+"<br><br>Name of Student:"+f2.firstChild.nodeValue +"<br><br>Lives in :"+f3.firstChild.nodeValue+"<br><br>Contact Details:"+f4.firstChild.nodeValue;
//accessing XML elements by name
var t=xmlDoc.getElementsByTagName("stname");
var f=xmlDoc.getElementsByTagName("mobile");
disp=disp +"<br><br><b>Accessing XML elements by name</b><br>Student Name: " +t[0].firstChild.nodeValue+ " <br><br>Call: "+f[0].firstChild.nodeValue;
document.getElementById('div1').innerHTML=disp;
}
</script>
</head>
<body>
<h1 style="background-color:black;color:white">Handling XML in AJAX Application</h1>
<button onClick="getData()">Get the Student Information</button>
<br><br><br>
<div id="div1">
text goes here...........................
</div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
xml file
student.xml
<?xml version="1.0" encoding="UTF-8"?>
<student1>
<prn>121</prn>
<stname>Vijay Sharma</stname>
<city>Chiplun</city>
<mobile>94232942090</mobile>
</student1>
I changed my XML file.It is working properly with following line of code
var t=xmlDoc.getElementsByTagName("stname");
var f=xmlDoc.getElementsByTagName("mobile");
disp=disp +"<br><br><b>Accessing XML elements by name</b><br>Student Name: " +t[0].firstChild.nodeValue+ " <br><br>Call: "+f[0].firstChild.nodeValue;
But I found error with following line of code
a=xmlDoc.documentElement;
f1=a.firstChild;
f2=f1.nextSibling;
f3=f2.nextSibling;
f4=f3.nextSibling;
disp="<b>using javascript properties</b><br>";
disp=disp+"PRN:"+f1.firstChild.nodeValue+"<br><br>Name of Student:"+f2.firstChild.nodeValue +"<br><br>Lives in :"+f3.firstChild.nodeValue+"<br><br>Contact Details:"+f4.firstChild.nodeValue;
It generate error as
Uncaught TypeError: Cannot read property 'nodeValue' of null
for following line of code
disp=disp+"PRN:"+f1.firstChild.nodeValue+"<br><br>Name of Student:"+f2.firstChild.nodeValue +"<br><br>Lives in :"+f3.firstChild.nodeValue+"<br><br>Contact Details:"+f4.firstChild.nodeValue;
So script does not work for nodeValue property.
Is nodeValue property is deprecated? If so ,then what I can used instead of nodeValue.
Please help.

Possible to use getElementsByClassName with an external HTML file?

I have a test.html file that looks like this:
<!DOCTYPE html>
<html>
<body>
<div class="outside">
<div class="inside">
FOO
</div>
</div>
<div class="outside">
<div class="inside">
BAR
</div>
</div>
</body>
</html>
Which I can simply parse like this:
<script>
var x = document.getElementsByClassName("outside");
for (var i=0;i<x.length;i++)
document.write(x[i].getElementsByClassName("inside")[0].childNodes[0].nodeValue);
</script>
To get the result I want:
FOO
BAR
But I would like to parse the content of test.html in another HTML file. I've tried using XMLHttpRequest like this:
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","test.html",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByClassName("outside");
for (var i=0;i<x.length;i++)
document.write(x[i].getElementsByClassName("inside")[0].childNodes[0].nodeValue);
But that gives me the following error:
TypeError: null is not an object (evaluating 'xmlDoc.getElementsByClassName')
Using all files on my local web server so shouldn't be any issues with access. I know that this certainly isn't the most modern way of parsing but its something I'm just gonna be using locally for a hobby project. But if you have any suggestions on how to solve this with jQuery for example, I'm open to any ideas.
It is hard to use responseXML when the document is not HTML.
You would need to set the html of a div with the responseText and query that.
var str = "<ul><li>1</li><li>2</li>"; //xmlhttp.responseText;
var div = document.createElement("div");
div.innerHTML = str;
var lis = div.getElementsByTagName("li");
for (var i=0;i<lis.length; i++) {
console.log(lis[i].textContent);
}

parsing a xml file using javascript does not givethe required result

I am trying to parse a XML-file using java-script. Actually, I read many tutorials to find out how to parse the data from the XML-file correctly, and I found that I am on the right way.
Concerning the loadXMLDoc(dname) function, I passed the path of the XML-file to loadXMLDoc function as follows:
var dname = "D:\files\files\Schriftsteller.xml";
function loadXMLDoc(dname)
But still the parsing does not give me the desired result, I want to display the name in the following tag
<name>Jane Austin</name>
but the web browser does not display it, I am using Chrome.
Please, (1) Let me know where my mistake is? (2)what extension the parser file should be saved under(.HTML/.js)
Please find below the XML-file and the java-script file
XML file:
<?xml version="1.0" ?>
<Schriftsteller>
<Englischsprache>
<Dichtung>
<fueller>
<name>Jane Austin</name>
<name>Rex Stout</name>
<name>Dashiell Hammett</name>
</fueller>
</Dichtung>
</Englischsprache>
</Schriftsteller>
JavaScript File.html(Parser):
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet" href="readXML.css" type="text/css">
<title>Read First Child</title>
<!-- <xml ID="Schriftsteller" SRC="D:\files\files\Schriftsteller.xml"></xml> -->
<script language="JavaScript">
var dname = "D:\files\files\Schriftsteller.xml";
function loadXMLDoc(dname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",dname,false);
xmlDoc.send();
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(dname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
function findWriter()
{
var schriftstellerKnoten, SpracheKnoten;
var FuellerKnoten, DichtungKnoten, Anzeige;
myXML = document.all(dname).XMLDocumentalert(dname);
SchriftstellerKnoten = myXML.documentElement;
SpracheKnoten = SchriftstellerKnoten.firstChild;
DichtungKnoten = SpracheKnoten.firstChild;
FuellerKnoten = DichtungKnoten.firstChild;
NameNode = FuellerKnoten.firstChild;
Anzeige = NameNode.firstChild.nodeValue;
document.write(Anzeige);
}
</script>
</head>
<body onload="loadXMLDoc(dname)">
<span ID="blueBack">Read firstChild</span>
<div>
<form name="show">
<input type=text name="me">
<input type="button" value="Display Writer"
onClick="findWriter()">
</form>
</div>
</body>
First your XML-Document has to be well-formed.
So for every tag you open add another tag to close it (like you do with the name-tag). The closing tag has to be same as the opening, except for a / in the beginning
Also you have to watch the case (well-formed XML is case-sensitive). The tag
<EnglischSprache> is different from <Englischsprache>
Try it like this:
<?xml version="1.0"?>
<Schriftsteller>
<EnglischSprache>
<Dichtung>
<fueller>
<name>Jane Austin</name>
<name>Rex Stout</name>
<name>Dashiell Hammett</name>
</fueller>
</Dichtung>
</EnglischSprache>
</Schriftsteller>
Then in the JS-File, maybe you should try calling the function loadXMLDoc.
Looks like you're just defining it.
Try it like this:
<body onload="loadXMLDoc(dname)">
Better now?

Cannot call method 'addEventListener' of null error

I write some javascript to get the weather information from the url. But the google Chrome shows the error:
Uncaught TypeError: Cannot call method 'addEventListener' of null weather.html:37
(anonymous function)
Any suggestions for fixing this? Thanks!
<html>
<head>
<title>My weather</title>
<script type="text/javascript">
function fetchWeather(){
var xmlHttp = new XMLHttpRequest(); // Initialize our XMLHttpRequest instance
xmlHttp.open("GET", "http://classes.engineering.wustl.edu/cse330/content/weather_json.php", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);
}
function ajaxCallback(event){
var htmlParent = document.getElementById("weatherWidget"); // Get the HTML element
var jsonData = JSON.parse(event.target.responseText);
var loc = document.getElementById("weatherWidget").getElementsByClassName("weather-loc")[0];
loc.appendChild(document.createTextNode(jsonData.location.city+" "+jsonData.location.state));
var humidity = document.getElementById("weatherWidget").getElementsByClassName("weather-humidity")[0];
humidity.appendChild(document.createTextNode("Humidity: "+jsonData.atmosphere.humidity+"%"));
var temp = document.getElementById("weatherWidget").getElementsByClassName("weather-temp")[0];
temp.appendChild(document.createTextNode("Currently: "+jsonData.current.temp));
var tomorrow = document.getElementById("weatherWidget").getElementsByClassName("weather-tomorrow")[0];
tomorrow.appendChild(document.setAttribute("src", jsonData.current.temp));
tomorrow.alt = jsonData.tomorrow.text;
tomorrow.src = "http://us.yimg.com/i/us/nws/weather/gr/"+jsonData.tomorrow.code+"ds.png"
var dayaftertomorrow = document.getElementById("weatherWidget").getElementsByClassName("weather-dayaftertomorrow")[0];
dayaftertomorrow.appendChild(document.setAttribute("src", jsonData.current.temp));
dayaftertomorrow.alt = jsonData.dayafter.text;
dayaftertomorrow.src = "http://us.yimg.com/i/us/nws/weather/gr/"+jsonData.dayafter.code+"ds.png"
}
document.getElementById("update").addEventListener("click", fetchWeather, false); // bind fetchWeather() to the DOMContentLoaded event
//so that your weather widget is automatically initialized
//when the page is loaded
</script>
</head>
<body>
<div class="weather" id="weatherWidget">
<div class="weather-loc"></div>
<div class="weather-humidity"></div>
<div class="weather-temp"></div>
<img class="weather-tomorrow" />
<img class="weather-dayaftertomorrow" />
</div>
<button id="update">Update</button>
</body>
</html>
The update element doesn't exist yet when you try to access it.
Either put the document.getElementById('update')... line at the end of the <body> element, or put it in a window.onload handler.

Using Ajax to display the values of an asynchronous function

I'm building a project that uses a function called Chat.fetch(); it's an asynchronous function that pulls an array of strings from the server. It's an ajax function that for purposes of the project is already defined, I just have to call it correctly. There is another function we are given called Chat.display() which takes a string and displays it in bulleted form on the console. Right now this is what I've got:
I'm getting an error that says cannot read property length of undefined. So I guess.length is undefined for superArray? The goal is to create this function and use it as the call back function for Chat.fetch(). Do you guys have any idea why I'm getting this .length error? I'm pretty confused. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://chatbuilder.hackreactor.com/ChatBuilder.js"></script>
</head>
<body>
<script>
Chat.guide.start();
<h2>Borken Chat</h2>
<input class="draft" type="text"/> <button class="send" disabled>send</button>
<ul class="messages">
<script>
var list;
var superArray=[];
darray=function(superArray){
var y=superArray.length;
for(i=0;i<y;i++){
Chat.display(x[i]);
}
}
Chat.fetch(darray(list));
</script>
</ul>
</body>
Here's a simple page that uses Ajax
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","<<URL>>",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Results will go here</h2></div>
<button type="button" onclick="loadXMLDoc()">Get Results</button>
</body>
</html>
See where the xmlHttp.responseText is used? That's where you'll get your strings.
I don't have any clue what code you have, but the basic idea is something like this (using jQuery, don't know if that is in your stack or not). And this assumes Chat.fetch() is synchronous, otherwise you'll need to trigger an event when it's done or use a promise or something.
messages = Chat.fetch();
for (i=0; i<messages.length; i++) {
$('#chat-window').append( '<br>' + messages[i] );
}

Categories