parse xml with javascript for html - javascript

I am trying to get some information from the Yahoo Console for weather conditions. The xml result tree from Yahoo looks like this: result tree
I am able to get things that are only one level deep with the code I have. My variable 'beta' is for the title which works beautifully. The second variable is 'alpha' which will not work. I believe it has to do with how I call for it 'item.condition.temp' and with the node values.
I am very new to this so please list any sources you use as it will help me going forward.
<!DOCTYPE html>
<html>
<head>
<p id="alpha"></p>
<p id="beta"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open('GET', 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2444827&diagnostics=true', true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById('beta').innerHTML =
xmlDoc.getElementsByTagName('title')[0].childNodes[0].nodeValue;
document.getElementById('alpha').innerHTML =
xmlDoc.getElementsByTagName('item.condition.temp')[0].childNodes[0].nodeValue;
}
</script>

I would suggest adding &format=json to your URL to make it this:
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2444827&diagnostics=true&format=json
Then parse the resulting JSON which is a more JavaScript way of doing it.

Related

PHP called by xhttp returns JavaScript function. How can I call the function inline? [duplicate]

This question already has answers here:
Executing <script> elements inserted with .innerHTML
(23 answers)
Closed 8 months ago.
I have a JavaScript function that gets data and a function statement from PHP via XMLHttpRequest.How do I call the function that the PHP returned? It doesn't seem to exist. I'm totally lost as to how to make this happen.
Here are test files that better explain it:
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function main(){
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/test2.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('foo=bar');
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById('testDiv').innerHTML = xhttp.responseText;
if (typeof injectedJS === "function") {
console.log('yes');
}else{
console.log("no");
}
}
};
};
</script>
</head>
<body onLoad=main()>
<div id="testDiv"></div>
</body>
</html>
test2.php
<?php
echo("<h1>Hello!</h1>");
echo("<script>function injectedJS() {var foo='bar';}</script>");
?>
The "Hello!" text is being displayed but "no" is logged to the console.
Thanks in advance for any help or a steer in the right direction,
John
Adding script tags using innerHTML won't execute those tags
Not even adding them through other methods like using DOMParser works
What you need to do is for each script tag you added, you use document.createElement('script') and duplicate the content, then add it to the DOM
const html = `<h1>Hello!</h1>
<scrpt>function injectedJS() {var foo='bar';}</scrpt>`.replaceAll('scrpt', 'script');
// ignore the replaceAll - seems snippets are careful about script tags - this is just dummying up the received data anyway
function main() {
// this is what you put inside
// if (xhttp.readyState == 4 && xhttp.status == 200) {
const tgt = document.getElementById('testDiv');
// add the html to the target node
tgt.innerHTML = html;
// process any script tags in the target node
tgt.querySelectorAll('script').forEach(scr => {
// create a new script tag
const newscript = document.createElement('script');
// copy the contents to the new script tag
newscript.textContent = scr.textContent;
// add new script directly after the current location
scr.insertAdjacentElement('afterend', newscript);
// remove old script - not strictly required
scr.remove();
});
if (typeof injectedJS === "function") {
console.log('yes');
} else {
console.log("no");
}
}
main();
<div>Test</div>
<div id="testDiv"></div>
By the way, instead of
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4 && xhttp.status == 200) {
// your code
}
}
do
xhttp.onload = function(){
// your code
}
or better still use fetch for cleaner looking code, but that's just opinion so not important

How can I get the content of multiple files at a time using AJAX on page load in javascript?

I am finding a way to load multiple files at a time in my html document using vanilla AJAX ( I don't want any dependecy, the way I will get using jQuery ). Here is a piece of code I grabbed from W3schools' AJAX Documentation. :
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.querySelector("#tst").innerHTML = this.responseText;
}
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
I am pretty new to AJAX. So, I have a confusion. The above function works fine, but I have multiple files to load and I don't want to call this function multiple times, to load the files. Let me describe my desired output. I am imagining the syntax of the updated function will be :
loadDoc(["one.txt", "two.txt", "three.txt"])
So, we observe that the input will be an array. And now the ouput will follow this format :
content of "one.txt" + break + content of "two.txt" + break + content of "three.txt" and so on....
If the content of "one.txt" is "Hello World !", content of "two.txt" is "I love", and content of "three.txt" is "Javascript", the output will be :
Hello World !
I love
Javascript
So, can you please help me update my code ?
Pass the list of files to load to a PHP/ASP/whatever page which assembles the text for you.
function loadDoc(files) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.querySelector("#tst").innerHTML = this.responseText;
}
}
xhttp.open("GET", "ajax_info.php?files="+files, true);
xhttp.send();
}
The files parameter could be a comma delimited list, which the page uses to get the contents and assemble it into a single return string.

XMLHttpRequest to get the content of a JSON file but it returns [object object]

I am following a guide from w3schools trying to understand JSON better.
This is their code
https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
This is their sample JSON file
https://www.w3schools.com/js/json_demo.txt
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>
<p>Take a look at json_demo.txt</p>
</body>
</html>
I have another example JSON file here that I want to use
https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json
Using the same code, apart from changing
document.getElementById("demo").innerHTML = myObj.name;
to
document.getElementById("demo").innerHTML = myObj;
It doesn't seem to bring back anything apart from [object object] and I cannot understand why, Could someone please help, thanks
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj;
}
};
xmlhttp.open("GET", "https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json", true);
xmlhttp.send();
</script>
</body>
</html>
If you want to print the received JSON object to the DOM, you'll need to turn it into a string. To do this, use JSON.stringify(responseText).

Hide a questiomark in url?

I had url which looks like http://localhost/dashboard/index.php?id=1 so that i would pass the value in url as per use and switch the dashboard accordingly. All i wanted is url should be visible like http://localhost/dashboard/index.php or even http://localhost/dashboard/index.php/1. I want to hide or replace a url string(for visibility) and not to redirect which i tried using htaccess. can we do that using JavaScript??
You can push state in browser history javascript. This will change your current page's url without redirecting to new url. Try below code in page load event.
history.pushState("", "", "1");
You can use AJAX to get your data from the php file and display the content on your browser.
This will avoid redirection and also the url will remain clean.
Haven't tried it but here's what you can do:
<!DOCTYPE html>
<html>
<body>
<p><span id="dashboardView"></span></p>
<span class="btn" val="1" onclick="showDashboard(this)">Dashboard 1</span>
<script>
function showDashboard(elem) {
var xhttp;
var val = elem.getAttribute("val");
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("dashboardView").innerHTML = this.responseText;
}
};
xhttp.open("GET", "dashboard/index.php?id="+val, true);
xhttp.send();
}
</script>
</body>
</html>
var urlStr = 'http://localhost/dashboard/index.php?id=1';
var nextURL = urlStr.replace("?", "");
alert(nextURL);

Cant read properly XML from Javascript

I am trying to read a XML file with Javascript , it is for a assignment in school so i cant use jQuery it has to be Javascript. Basicly i can read ONE value but not the other
This is my JS that is resposible for reading the XML value. It will read startLng but it gives me startLat is undefined. But if i check the XML file the startLat is not undefined. I cant see what the problem is here.
What i am trying to do is to get the LatitudeDegrees and LongitudeDegrees from the XML file. But it only gives me the LongitudeDegrees and says the LatitudeDegrees is undefined. What am i doing wrong here?
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
getLatLang(xmlhttp);
}
};
xmlhttp.open("GET", "G1.TCX", true);
xmlhttp.send();
}
function getLatLang(xml)
{
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("Trackpoint");
startLat = x[0].getElementsByTagName("Position")[0].getElementsByTagName("LatitudeDegrees")[0].childNodes[0].nodeValue;
startLng = x[0].getElementsByTagName("Position")[0].getElementsByTagName("LongitudeDegrees")[0].childNodes[0].nodeValue;
}
This is the XML file
<Trackpoint>
<Time>2008-10-28T15:58:22Z</Time>
<Position>
<LatitudeDegrees>59.4111992</LatitudeDegrees>
<LongitudeDegrees>13.5304104</LongitudeDegrees>
</Position>
<AltitudeMeters>85.6945801</AltitudeMeters>
<DistanceMeters>0.2149343</DistanceMeters>
<HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
<Value>116</Value>
</HeartRateBpm>
<SensorState>Absent</SensorState>
<Extensions>
<TPX xmlns="http://www.garmin.com/xmlschemas/ActivityExtension/v2" CadenceSensor="Footpod"/>
</Extensions>
</Trackpoint>
This has been solved.
The problem was i did not have a document load.

Categories