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.
Related
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;
}
I have a local text file present in the location /home/myname/Desktop/iot/public/sensordata.txt. This file has to be read in JavaScript when a button is clicked on a web page. My code is given below:
<html>
<head>
<title>Humidity</title>
</head>
<body>
<h3>Humidity page</h3>
<table>
<tr>
<td>
<button type="button" onclick="humidgraph('public/sensordata.txt','chartContainer')">View live humidity data</button>
</td>
</tr>
</table>
<p><div id="chartContainer" style="height: 300px;width= 100%;"></div></p>
<script type="text/javascript">
function humidgraph(datasource,divid){
var i=0;
var xVal,yVal;
var humidity=[],time=[],dps=[];
var fileread=false;
var obj=document.getElementById(divid);
if(window.XMLHttpRequest){
fileread=new XMLHttpRequest();
}else if(window.ActiveXObject){
fileread=new ActiveXObject("Microsoft.XMLHTTP");
}
if(fileread){
fileread.open("GET",datasource);
document.getElementById("chartContainer").innerHTML=fileread.responseText;
}
fileread.onreadystatechange=function(){
if((fileread.readyState===4 || fileread.readyState===0) && fileread.status===200){
var text=fileread.responseText;
text.split(/\n/).forEach(function(item){
humidity.push(Number(item.match(/Humidity(.\d+[.]\d+)/)[1]));
});
text.split(/\n/).forEach(function(item){
time.push(Number(item.match(/time(.\d+[.]\d+)/)[1]));
});
}
}
while(i<time.length){
xVal=time[i];
yVal=humidity[i];
dps.push({x: xVal,y: yVal});
i++;
}
}
</script>
</body>
</html>
However, no data is being printed on the html page, even though innerHTML is being used. Is there something wrong with my file path? Please help.
You need to run a webserver and make the get request to a URI on that server, rather than making the get request to a file (you get a "cross origin requests" error).
Then change:
humidgraph('public/sensordata.txt','chartContainer')
to read something like:
humidgraph('http://localhost/public/sensordata.txt','chartContainer')
and the initial request page needs to be loaded from that server as well.
Additionally you should do your request in the below order:
fileread.onreadystatechange=function (){
...
};
...
fileread.open("GET", datasource);
fileread.send();
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?
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] );
}
I am using Ajax to do a live search and all i want is the data t be displayed in a div called "results". However when im ding the search, it displays the search form again and then the results div. How do I go by solving this?
Here is the ajax code:
function finding(str)
{
if (str.length==0)
{
document.getElementById("results").innerHTML="";
return;
}
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("results").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","toy_search.jsp?query="+str,true);
xmlhttp.send();
}
I have added the search page here:
<%#page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*, toyShop.*,java.util.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Toy Search</title>
<script type="text/javascript" src="js/search.js"></script>
</head>
<body>
<h2>Toy Search</h2>
Find toy: <input type="text" name="query" id="query" onkeyup="finding(this.value)" /><br>
<%
ToyManager toyM = new ToyManagerImp();
ArrayList<ToyData> toy_data = new ArrayList<ToyData>();
String toyName = null;
String toyBrand = null;
String desc = null;
if(!MySQLConn.getInstance().isConnected()){
MySQLConn.getInstance().connect();
}
if(request.getParameter("query") != null && !request.getParameter("query").equals("")){
String query = request.getParameter("query");
toy_data = toyM.searchToy(MySQLConn.getInstance(), query);
}
%>
<div id="results">
<%
if(toy_data != null && !toy_data.isEmpty()){
for(int i = 0; i < toy_data.size(); i++){%>
<%=toy_data.get(i).getToyName()%>
<%= "<br>"%>
<% }
}
%>
</div>
</body>
</html>
Without seeing the rest of your code, it's hard to tell. If you want to remove the search field from the page and just display the results, I suggest somewhere in the following function you add a line of javascript that updates the css style on your search div to display: hidden.
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("results").innerHTML=xmlhttp.responseText;
}
}
You are asking for a complete web page with your Ajax call, and you're getting one back. It's working as designed, as they say. The problem is not with your Ajax, but with what you are returning from the server. You should be returning search results data, not a web page that happens to have search results data on it. Make the display of the static HTML elements on the page conditional on the method used to get the page. For instance, if the Ajax call looked like this:
xmlhttp.open("GET","toy_search.jsp?query="+str+"&format=fragment",true);
you would hide the HTML because of the &format=fragment part of the URL, leaving you with only the HTML that should be injected into the results div. In normal (non-Ajax) use, where the page is either being opened initially or there is a direct link to search results, the &format=fragment portion of the URL would not be present, and the user would load the entire page.