I'm currently using this code to read a XML file:
<script type="text/javascript">function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (true) {
myFunction(xhttp);
}
};
xhttp.open("GET", "../wp-content/uploads/2015/12/zuiderspel.xml", true);
xhttp.send();
}
function myFunction(xml){
console.log(xml.response);
var x, i, xmlDoc, table;
xmlDoc = xml.response;
x = xmlDoc.getElementsByTagName("name")[0];
console.log(x);
}
loadDoc();
</script>
(By the way, I have to put 4 spaces in front of each line in Stackoverflow to get it in a codeblock, which is tedious and ruins the indents. How can I do this easier?)
My question: I get the error
(index):168 Uncaught TypeError: xmlDoc.getElementsByTagName is not a function
Why is this? Using the example found at http://www.w3schools.com/xml/tryit.asp?filename=try_dom_xmlhttprequest_xml this should be right, yet, it's not..
Thanks!
The example says xmlDoc = xml.responseXML while you are saying xmlDoc = xml.response.
Related
I don't need anything fancy on this. I'm loading a Q&A page. The Q&A I want on a seperate file so I can just update the file and it will update the page the next time it's loaded by someone.
I created a file "faq.xml" and am trying to load that in to my faq.php file.
<p id="xmlp" class="content" style="text-align: center">
<!-- XML should go here -->
</p>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
myFunction(this);
xmlhttp.open("GET", "faq.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var x, i, xmlDoc, table;
xmlDoc = xml.responseXML;
table = "<tr><th>Question</th><th>Answer</th></tr>";
x = xmlDoc.getElementsByTagName("faqs")
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("question")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("answer")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("xmlp").innerHTML = table;
}
</script>
For whatever reason, it's not loading anything. The XML file currently has this...
<?xml version="1.0" encoding="UTF-8"?>
<faqs>
<question>When do you fly?</question>
<answer>We fly at sunrise weather permitting. Flights are more peaceful and the winds are great. We even fly low enough to have a conversation with those less fortunate on the ground. People tend to hang around at launch and landings to see what it’s all about.</answer>
</faqs>
Any suggestions? I'm new to XML (this is my first one).
Thank you in advanced.
I put an alert in to ensure the js was getting started and it did function.
<script>
loadXMLDoc();
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
alert();
myFunction(this);
xmlhttp.open("GET", "faq.xml", true);
xmlhttp.send();
}
Still not sure where the hold up is.
I did more testing and I think I found where at least something is wrong...
<p id="xmlp" class="content" style="text-align: center">
<!-- XML should go here -->
</p>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
myFunction(this);
xmlhttp.open("GET", "faq.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var x, i, xmlDoc, table;
xmlDoc = xml.responseXML;
table = "<tr><th>Question</th><th>Answer</th></tr>";
alert("This one works");
x = xmlDoc.getElementsByTagName("faqs")
alert("This one does not work");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("question")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("answer")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("xmlp").innerHTML = table;
}
</script>
This is a basic example of loading an xml file via AJAX from https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_xml:
<body onLoad="loadXMLDocument('someXMLfile.xml')">
<p>
<b>Status:</b> <span id="statusInfo"></span>
</p>
<p>
<b>Status text:</b><span id="statusTextInfo"></span>
</p>
<p>
<b>Response:</b> <span id="xmlContent"></span>
</p>
<script>
function loadXMLDocument(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('statusText').innerHTML = this.status;
document.getElementById('statusTextInfo').innerHTML = this.statusText;
document.getElementById('xmlContent').innerHTML = this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
</script>
</body>
This will load an XML file into Javascript.
Though as I mentioned, if you're getting to grips with AJAX, PHP and XML all at once
the straightforward way might be to make an AJAX call to PHP and process the xml using a php function on the server.
The 4/200 status codes make AJAX debugging a little easier.
I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}
UPDATED:
I'm trying to parse a response from a URL but have no idea if I'm doing it correctly.
The URL returns the following JSON:
{"make":"truck","date":"23 July 2009","colour":"pink"};
If i replace var newtext = xhttp.responseText; with
var newtext = '{"make":"truck","date":"23 July 2009","colour":"pink"}';
it works but as soon as i go back to the xhttp.responseText it just shows a blank page.
The code I'm using is:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
xhttp.open("GET", "https://url.com", false);
xhttp.send();
var newtext = xhttp.responseText;
var obj = JSON.parse(newtext);
document.getElementById("demo").innerHTML =
obj.make + "<br>" +
obj.colour + "<br>" +
obj.date;
</script>
</body>
</html>
You haven't defined your variable xhttp, but you are trying to call functions on it. This is resulting in the Uncaught ReferenceError error and causing the rest of the code not to run. To create an XMLHttpRequest object as you appear to be trying to do, put this at the top of your script.
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// the object actually exists here now so the functions can be called on it
xhttp.open("GET", "https://url.com", false);
xhttp.send();
...
Then you can continue on with the rest of your code, assured that your xhttp object has been initialized.
I don't normally recommend using w3schools, but the above code was copied from http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
I am trying to get my array to read from a xml file and post into html.(My assignment is to get ajax to run from xml) My script so far is
<script type="text/javascript">
var xmlDoc;
var xmlhttp;
function loadinfo()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = readinfo;
xmlhttp.open("GET", "Info.xml", true);
xmlhttp.send();
}
function readinfo()
{
if (xmlhttp.readyState == 4) {
xmlDoc = xmlhttp.informationXML;
var items = xmlDoc.getElementsByTagName("info")
var var1 = items[0].getAttribute("campus-email", "campus-phone", "online-email", "online-phone");
}
}
I made sure I added this to the body > body onload="loadinfo();"
This line:
xmlDoc = xmlhttp.informationXML;
should be:
xmlDoc = xmlhttp.responseXML;
I am trying to create a simple XML node with text "New node!"
var xmlDoc = loadXMLDoc("myFile.xml");
var newElem = xmlDoc.createElement("elem");
newElem.innerHTML = "New node!";
Where loadXMLDoc() is
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname, false);
xhttp.send();
return xhttp.responseXML;
}
But the code does not work. I expect the XML file to have a new node "<elem>" with "New node!" in it, but it was still the same. I have no idea why. There were no error messages.
How do I get my code to work?
Your code is creating a new element, but you are not appending it to the XML.
See the example here: https://developer.mozilla.org/en-US/docs/Web/API/document.createElement#Example