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] );
}
Related
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.
I am tryint to create a little RadioPlayer that works online . Now this is the JavaScript Code that i have
function changeLink(link)
{
/* this changes the link and plays the radio*/
var radio= document.getElementById("radio");
radio.src = link;
radio.play();
}
function jsonLoad()
{
var xmlhttp = new XMLHttpRequest();
var url = "playList.txt";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
readJSON(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function readJSON(obj)
{
var list = "<ui>";
for (var i = 0; i < obj.length ; i++)
{
list += "<li><a href='javascript:changeLink(" +"\"" + obj[i].radioLink + "\"" +");'>" + obj[i].name + "</a></li>";
}
list += "</ui>";
document.getElementById("radioLoad").innerHTML = list;
}
Also this is the HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> My Radio Player</title>
<script src="Script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="jsonLoad()">
<p>This is the link that i will change his property</p>
<audio id="radio" src="#" controls autoplay preload="auto" ></audio>
</audio>
<br>
<p id="radioLoad">
</p>
</body>
Things is that locally the JSON File is perfectly working, and the webpage shows as i expected. When i put it on a server though, it's like the JSON file is not loaded and the other fuction (readJSON(myArr);) is not fired. Seems that there is something wrong with the IF Condition but i don't know excatly why. Can somebody help me?
EDIT: Seems that the code only works locally in Google Chrome. In internet explorer the links are generated but they don't play the radio when i click on them. Also on the iphone simulator that i tested, the audio tag is not working properly. I will try on different webbrowsers also.
EDIT2: it works now. I managed to figure outthe issue. It was nothing wrong with the code, it was with the server i was hosting on. So i changed the web hoster and now it works. You can see it here:
http://radioplay4all.16mb.com/
Thank you anyway :)
Without debugging it myself I can't be sure, but I'm pretty sure that your problem is in your readJSON() function, when you try to get the .length property of an object (JSON.parse() returns a javascript object), since objects don't have a .length property. To find the number of keys an object has, you could use Object.keys(myArr).length. So in your for loop, obj.length is Null, so i can't be less than Null, so it doesn't execute. So if you replace i < obj.length with i < Object.keys(obj).length that should fix the problem.
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 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.