How to parse XML using AJAX in html? - javascript

I'm trying to parse XML by using AJAX. However there were a few errors which i got saying my "html is not defined"
Basically what I want to do is to parse a specific amount of data from my XML codes and display it using HTML webpage .
The below is the list of bugs in console when I tried to run the script
at displayCountrylist (test2.html:136)
at handleStatusSuccess (test2.html:61)
at readyStateChangeHandler (test2.html:32)
at XMLHttpRequest.xhttp.onreadystatechange (test2.html:16)
I tried to do everything to debug but still failed. Any one help please?
<html>
<script>
function makeAjaxQueryCountrylist()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
readyStateChangeHandler(xhttp);
};
xhttp.open("GET", "A3_CtryData_dtd_Sample.xml", true);
xhttp.send();
}
function readyStateChangeHandler(xhttp)
{
if (xhttp.readyState == 4)
{
if(xhttp.status == 200)
{
handleStatusSuccess(xhttp);
}else
{
handleStatusFailure(xhttp);
}
}
}
function handleStatusFailure(xhttp){
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
function handleStatusSuccess(xhttp)
{
var xml = xhttp.responseXML;
var countrylistObj = parseXMLCountrylist(xml);
displayCountrylist(countrylistObj);
}
function parseXMLCountrylist(xml)
{
var countrylistObj = {};
var countrylistElement = xml.getElementsByTagName("CountryList")[0];
var recordElementList = countrylistElement.getElementsByTagName("CountryRecord");
countrylistObj.recordList = parseRecordElementList(recordElementList);
return countrylistObj;
}
function parseRecordElementList(recordElementList)
{
var recordList = [];
for(var i=0; i < recordElementList.length; i++)
{
var recordElement = recordElementList[i];
var recordObj = parseRecordElement(recordElement);
recordList.push(recordObj);
}
return recordList;
}
function parseRecordElement(recordElement)
{
var recordObj = {};
var countrycodeElement = recordElement.getElementsByTagName("country-code")[0];
recordObj.countrycode = Number(countrycodeElement.textContent);
var nameElement = recordElement.getElementsByTagName("name")[0];
recordObj.name = nameElement.textContent;
var alpha2Element = recordElement.getElementsByTagName("alpha-2")[0];
recordObj.alpha2 = alpha2Element.textContent;
var alpha3Element = recordElement.getElementsByTagName("alpha-3")[0];
recordObj.alpha3 = alpha3Element.textContent;
var capitalcityElement = recordElement.getElementsByTagName("capital-city")[0];
recordObj.capitalcity = capitalcityElement.textContent;
return recordObj;
}
function displayCountrylist(countrylistObj)
{
for(var i=0; i < countrylistObj.recordList.length; i++)
{
var recordObj = countrylistObj.recordList[i];
html += "country-code: " + recordObj.countrycode;
html += "<br />";
html += "name: " + recordObj.name;
html += "<br />";
html += "alpha-2: " + recordObj.alpha2;
html += "<br />";
html += "alpha-3: " + recordObj.alpha3;
html += "<br />";
html += "capital-city: " + recordObj.capitalcity;
html += "<br />";
}
var displayDiv = document.getElementById("display1");
displayDiv.innerHTML = html;
}
</script>
<body>
<button onClick="makeAjaxQueryCountrylist()"> Region Info I (Format: region-fmt-1.xsl)</button>
<br /><br />
<div id="display1">
</div>
</body>
</html>
There isn't any problem with my XML codes so it has to be some error from here.

You got that error html is not defined because you are using html variable without declaring it. So, before the line
html += "country-code: " + recordObj.countrycode;
you have to write
let html = '';

Related

Is there something wrong with this javascript?

So this is externally linked, that works fine. But when I run it in the browser, it does not show anything. Is there anything wrong with this code?
var myheading = "This is my webpage!";
var text = "This JavaScript file makes use of Variables";
var linktag = "http://www.google.com/";
var begineffect = "<strong>";
var endeffect = "</strong>";
var linebreak = "<br />";
function numberone(myheading) {
document.write("<h2>" +myheading+ "</h2>");
}
numberone(myheading)
function numbertwo(text) {
document.write("<strong>" +text+ "</strong>");
}
numbertwo(text)
function numberthree(linktag) {
document.write( +linktag+ );
}
numberthree(linktag)
There are two extra + to remove in the document.write of the 'numberthree' function, i.e.:
var myheading = "This is my webpage!";
var text = "This JavaScript file makes use of Variables";
var linktag = "http://www.google.com/";
var begineffect = "<strong>";
var endeffect = "</strong>";
var linebreak = "<br />";
function numberone(myheading) {
document.write("<h2>" +myheading+ "</h2>");
}
numberone(myheading)
function numbertwo(text) {
document.write("<strong>" +text+ "</strong>");
}
numbertwo(text)
function numberthree(linktag) {
document.write(linktag);
}
numberthree(linktag)

Why did I get undefined values when trying to read xml file?

I am trying to read data from a xml file and display them in my html file, but when I am trying to display my values I get "undefined" values for all the values.
I am a really new with ajax and xml so excuse my code if its horrible! I will appreciate if someone got a really briefly answer.
Here's my xml file:
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2019-01-25">
<Cube currency="USD" rate="1.1346"/>
<Cube currency="JPY" rate="124.72"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="25.697"/>
<Cube currency="DKK" rate="7.4664"/>
<Cube currency="GBP" rate="0.86580"/>
....
My javascript code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
returndata(this);
}
};
xhttp.open("GET", "rates.xml", true);
xhttp.send();
}
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("currency")[0] +
"</td><td>" +
x[i].getElementsByTagName("rate")[0] +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
When I click the button I got the following result:
currency rates
undefined undefined
undefined undefined
undefined undefined
undefined undefined
.....
UPDATE Javascript code(fixed):
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 2; i <x.length; i++) {
table += "<tr><td>" +
x[i].getAttribute("currency") +
"</td><td>" +
x[i].getAttribute("rate") +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
Okay now it works, thank you very much, i started my variable from the value 2 because when i am trying to have a while loop like (x!=null) my webpage it still loading forever and then breaks down..
i tried that one:
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 0; i <x.length; i++) {
while (x!=null) {
table += "<tr><td>" +
x[i].getAttribute("currency") +
"</td><td>" +
x[i].getAttribute("rate") +
"</td></tr>";
}
}
document.getElementById("demo").innerHTML = table;
}

Javascript onmousehover event to connect information

So in my code I created a table pulling from an XML file that displayed two columns of information about plants. The goal of my program is to be able to hover over the first and print out the other information about that plant and print it in another section to the right of my table. The issue is that I am not gettign any console errors and the hover affect is not printing any information.
window.addEventListener("load", link_events);
var xhr = false;
function link_events() {
xhr = new XMLHttpRequest();
if(xhr) {
xhr.addEventListener("readystatechange", ShowFile);
xhr.open("GET", "plants.xml", true);
xhr.send();
} else {
alert("XHR not supported.");
}
}
function ShowFile() {
var i;
var title;
var cover;
var plant_table = "<table><tr><th>Common Name </th><th>Botanical Name </th></tr>";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//here we have gotten the file correctly
//loop through it and print out cover and title
var plantlist = xhr.responseXML.getElementsByTagName("PLANT");
//booklist is an array and each element is an object sub i
//so you have to use getElementBy something in order to pull the information
for (i = 0; i < plantlist.length; i++) {
var Common = plantlist[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Botanical = plantlist[i].getElementsByTagName("BOTANICAL")[0].firstChild.textContent;
plant_table += "<tr>" +
"<td class =\"plant\">" + Common + "</td>" +
"<td>" + Botanical + "</td>" +
"</tr>";
}
plant_table += "</table>";
document.getElementById("outarea").innerHTML = plant_table;
}
var plants = document.getElementsByClassName("plant");
for (i=0; i < plants.length; i++) {
plants[i].onmouseover = HoverChoice;
}
}
function HoverChoice() {
var input = xhr.responseXML.getElementsByTagName("PLANT");
for (i = 0; i < input.length; i++) {
Common = input[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Zone = input[i].getElementsByTagName("ZONE")[0].firstChild.textContent;
var Light = input[i].getElementsByTagName("LIGHT")[0].firstChild.textContent;
var Price = input[i].getElementsByTagName("PRICE")[0].firstChild.textContent;
if (plants == this.innerHTML) {
document.getElementById("inarea").innerHTML =
"<h1>" + Common + "</h1>" + "<br />" + "<br />" +
"Zone: " + Zone + "<br />" +
"Light: " + Light + "<br />" +
"Price: " + Price;
}
}
}
}
you could try using addEventListener method instead and see whether it works?
plants.forEach(function(plant){
plant.addEventListener("onmouseover", HoverChoice);
});
or going with the original loop you made it would be
for (i=0; i < plants.length; i++)
{
plants[i].addEventListener("onmouseover", HoverChoice);
}
I'm not anything professional, a common problem I used to encounter in these kinds of event listening functions was that calling a global function sometimes fails but making the function on the spot inside the event listener would work like addEventListener("onmouseover" , function() { return 0; });

How to get this data using the loop?

How do i show all the data by using the loop to display all the data from json to html ?
ATM , I am able to print one of the data. but if i am using data[i] the code will not display any data.
I think I mess up the the concept of object and array.
please advice me , how to loop thru object , like array?
thanks
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET','https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data.weather ){
var x= data.weather[i].main;
weatherString+= "<p class='weather'>" + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
to get all data check for object and do recursive loop
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
//console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data) {
var x = data[i];
if(typeof(x) == "object") {
getHTML(x);
}
else {
weatherString += "<p class='weather'><b>" + i + "</b>: " + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for (var i in data.weather) {
var x = data.weather[i].main;
weatherString += "<p class='weather'>" + x + "</p>";
$.each(data.main, function(i, f) {
var main = "<div>" + i + ": " + f + "</div>";
$(main).appendTo("#main");
});
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
<div id="main"></div>
use foreach loop to iterate over all object
read more from here

Stuck trying to parse XML using AJAX and Javascript with XMLHttpRequest

Re-edit of the InnerHtml to show how many Div's will be included in the finished code. Also a re-edit of the start function which now does not work and I'm not sure at what point I broke it.
var fname = name;
function load()
{
var x = new XMLHttpRequest();
x.open ("GET", "file1.xml",true);
x.onreadystatechange = handleServerInput;
x.send();
xml =x.responseXML;
fname = xml.getElementsByTagName("name")[0];
name = fname.childNodes[0].data;
function handleServerInput()
{
if (x.readyState == 4 && x.status == 200)
{
function DisplayDiv()
{
var html = "";
html+= " <div id = \"displayOuter\">";
html+= " <div id = \"displayInner\">";
html+= " <p id = \"fname\">";
html+= " </p>";
html+= " </div>";
html+= " <div id = \"displayInner2\">";
html+= " </div>";
html+= " <div id = \"displayInner3\">";
html+= " </div>";
html+= " </div>";
return html;
}
function start()
{
document.body.innerHTML+=DisplayDiv();
var displayOuterDiv = document.getElementById("displayOuter");
displayOuterDiv.style.display= "block";
var innerdiv = document.getElementById('displayInner');
innerdiv.innerHTML = fname;
}
// alert ( this.responseText );
}
}
}
window.onload = load;
So I put the DisplayDiv function inside my handleServerInput function and that does imput the data to the HTML Div but only when it is set to false which I don't want. Can someone explain to me why this is? Here is an update of the code.
var fname = name;
function load()
{
var x = new XMLHttpRequest();
x.open ("GET", "file1.xml",false);
x.onreadystatechange = handleServerInput;
x.send();
function handleServerInput()
{
if (x.readyState == 4 && x.status == 200)
{
document.body.innerHTML+=DisplayDiv();
div = document.getElementById('displayInner');
div.innerHTML = fname;
}
function DisplayDiv()
{
var html = "";
html+= " <div id = \"displayInner\">";
html+= " <p id = \"fname\">";
html+= " </p>";
html+= " </div>";
return html;
}
}
xml =x.responseXML;
fname = xml.getElementsByTagName("name")[0];
name = fname.childNodes[0].data;
}
Try assigning fname before you use it. I assume you only want to use x.responseXML on a 200 response, so you should move
xml =x.responseXML;
fname = xml.getElementsByTagName("name")[0];
name = fname.childNodes[0].data;
into your if statement, somewhere before
div.innerHTML = fname;
happens

Categories