Reading XML from URL using Javascript - javascript

I am writing code to retrieve some part of an xml document. I am using Wolfram API (I am registered and I have an AppID.). So if I save the xml file locally after I execute the search command (variable "url" below),it works perfecly (if I have xmlDoc.load("query2.xml") where the xml is savedd in query2.url). However, I want to put a url instead, and get them on the fly rather than save the xml. I tried xmlDoc.load(url) but that didn't work, and after researching I found a function that's supposed to help retrieve this xml data from a tutorial website, but that didn't work either (it doesnt display anything on the page). How can I get the xml given a url?
Thanks in advance!
<body>
<div id="container" style="background-color:yellow"></div>
<script>
//load xml file
var url = "http://api.wolframalpha.com/v2/query?input=distance%20from%20london%20to%20california&appid=xxx";
if (window.ActiveXObject){
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false; //Enforce download of XML file first. IE only.
}
else if (document.implementation && document.implementation.createDocument)
var xmlDoc= document.implementation.createDocument("","doc",null);
if (typeof xmlDoc!="undefined") {
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;
}
xmlDoc.load(loadXMLDoc(url));
//xmlDoc.load("query2.xml");
}
else {
}
//Regular expression used to match any non-whitespace character
var notWhitespace = /\S/
function getnumber(){
//Cache "messages" element of xml file
var msgobj=xmlDoc.getElementsByTagName("plaintext")[1]
//REMOVE white spaces in XML file. Intended mainly for NS6/Mozilla
for (i=0;i<msgobj.childNodes.length;i++){
if ((msgobj.childNodes[i].nodeType == 3)&&
(!notWhitespace.test(msgobj.childNodes[i].nodeValue))) {
// that is, if it's a whitespace text node
msgobj.removeChild(msgobj.childNodes[i])
i--
}
}
//Get answer and display it in DIV:
document.getElementById("container").innerHTML=
xmlDoc.getElementsByTagName("plaintext")[1].childNodes[0].nodeValue
}
if (typeof xmlDoc!="undefined"){
if (window.ActiveXObject) //if IE, simply execute script (due to async prop).
getdaily()
else //else if NS6, execute script when XML object has loaded
xmlDoc.onload=getnumber
}
</script>
</body>

Related

Import XML with JavaScript function

I have a panel, that when clicked opens up and displays data. I would like to have the data come from a XML file.
The JavaScript function that I was using to display html text worked, so I was trying to use that function, but modify it to bring over the XML from another file.
The JavaScript function from the JS file:
function nameFunction () {document.querySelector("#collapse1> .panel-body").innerHTML = "Name works"};
The XML from the XML file
<dashboard>
<name>name goes here</name>
</dashboard>
The html file that calls the JS function:
<a data-toggle="collapse" href="#collapse1" onClick="nameFunction()" >Name</a>
Can the .innerHTML method be used for this task? If so, can someone provide an example?
function nameFunction () {
var xmlText = "<dashboard>"+
"<name>name goes here</name>"+
"</dashboard>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlText,"text/xml");
document.querySelector("#collapse1 > .panel-body").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}
hope this can help you ! (this works)
function nameFunction (){
var xhttp;
if (window.XMLHttpRequest) { // Create an instance of XMLHttpRequest object.
//code for IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "data.xml", false);
xhttp.send();
var xmlDoc = xhttp.responseXML;
document.querySelector("#collapse1 > .panel-body").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}
this works in firefox,(not in chrome - chrome doesn't have XMLHttpRequest API I guess)
so now you can parse xml file
you can import files using script tag.
<script id="xml" type="notjs" src="XX.xml"></script>
var xml = document.getElementById("xml");
Is this what you want?

DOMParser.parseFromString fails with XML5619: Incorrect document syntax

I have this javascript function that gets an xml file from a web site:
function getCCDfromHV() {
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// code for IE6, IE5
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var xml = xmlhttp.responseText;
document.getElementById("uploadResponse").innerHTML=xml;
xmlDom = createXmlDOM(xml);
}
}
xmlhttp.open("GET","../HVRawConnectorPHP/demo_app/GetCCDfromHV.php",true);
xmlhttp.send();
}
The xml is retrieved ok as I can see from the dump to .innerHTML. But createXmlDOM's parseFromString fails with "XML5619: Incorrect document syntax" as shown below:
function createXmlDOM(xml) {
console.log('createXmlDOM: the first 255 chars=' +xml.substring(0,255));
if (window.DOMParser){
var parser=new DOMParser();
xmlDom=parser.parseFromString(xml,"text/xml"); //fails with XML5619: Incorrect document syntax.
}
else { // Internet Explorer
xmlDom=new ActiveXObject("Microsoft.XMLDOM");
xmlDom.async=false;
xmlDom.loadXML(xml);
}
return xmlDom;
}
But if I copy the .innerHTML text and paste it into an editor and save it as a text file, load that file using FileReader, then send that text to createXmlDOM, it works fine!
So somehow the act of cut and pasting or file writing and reading does some kind of translation that makes it acceptable to parseFromString. Is there a way do do it without saving and reloading a file? It seems to be failing on the first character which is a '&' because the first char is really '<' but html changes that to &lt whereas loading it from text file doesn't.
I finally figured it out. The xml needs to be html decoded. I added the following function:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Which I found from here:
http://css-tricks.com/snippets/javascript/unescape-html-in-js/

Loaded XML Document is null (Javascript)

I am trying to load an XML document into Javascript so it can be outputted on a website, however when I load the XML document it is null, and so I get an exception each time I try to read from it. Here is my code:
CODE ON THE WEBPAGE
var xmlDoc;
loadXML();
function loadXML(){
xmlDoc = loadXMLDoc("http://www.tomrichardsonweb.co.uk/ABC/xml/pubs.xml");
}
function loadPub(){
if(xmlDoc != null){
document.getElementById('pub').innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}else{
alert("null");
}
loadXMLDoc Method
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;
}
XML file
< ?xml version="1.0" encoding="UTF-8" ?>
<pub>
<name>Bay Horse</name>
<description>Situated at the foot of the stunning Pennine Range, amidst the breathtaking landscape of Rivington, you will find The Bay Horse Inn. With open fires, cosy corners and a warm friendly atmosphere, this family run inn really does have something for everyone.
The perfect place to relax with family and friends our well stocked bar offers the finest cask ales, refreshing lagers and ciders, quality wines and spirits and a wide selection of soft drinks, teas and coffees.
For diners our chalkboards boast classic pub food, all freshly prepared and cooked to order, alongside a great range of award winning "Pieminister" pies.
And for those visiting the area on business or pleasure, or just passing through on a wider journey, and looking for somewhere to rest their heads then our bed and breakfast rooms could be just the answer! Our friendly team (and our friendly regulars!) will try to make your stay as enjoyable as possible.</description>
<web>N/a</web>
<email>N/a</email>
<phone>N/a</phone>
<image></image>
</pub>
I am constantly getting xmlDoc = null. What is the problem here?
EDIT: In Chrome, under the network tab, it says that the xml document has been loaded. I am testing all this on the server my website is hosted, and not from my machine.
first of all you should move all the inline scripts to the js file so that code is easy to manage, now as for your function
function loadPub(i, xml){....}
function loadXMLHTTP(url, callbackfn, args) {//callbackfn:fn you need to load after xml loads, args:argument array to pass to the call back function
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("No browser support for XML-HTTP-request object")
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
args.push( xmlhttp.responseXML);
callbackfn.apply(this,args)
}
}
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
}
function loadXML(){
xmlDoc = loadXMLHTTP("xml/pubs.xml",loadPub,[0]);
}
loadXML();
In this function the ajax request waits for the xml to load from the server and then it call the function that you pass in it with the args and the xml

how to style xml elements individually from an XPath javascript loop?

So i'm trying to pull selected data from an xml file using xpath (javascript in an html page). The only issue i'm having is: finding a way to style each value individually rather than (currently) only being able to style the entire stream at once.
I'm assuming this is just a matter of understanding javascript loops, but I would appreciate any quick help you may provide. Thanks.
The xml file is basically this: http://www.w3schools.com/xml/cd_catalog.xml
Here's the XPath / js code:
<script type="text/javascript">
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;
}
xml=loadXMLDoc("catalog.xml");
path="/catalog/cd[year=1985]/title | /catalog/cd[year=1985]/company | /catalog/cd[year=1985]/country";
// code for IE
if (window.ActiveXObject)
{
var nodes=xml.selectNodes(path);
for (i=0;i<nodes.length;i++)
{
document.write("<font color=\"red\">");
document.write(nodes[i].childNodes[0].nodeValue);
document.write("</font>");
document.write("<hr>");
}
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
var nodes=xml.evaluate(path, xml, null, XPathResult.ANY_TYPE,null);
var result=nodes.iterateNext();
while (result)
{
document.write("<strong>");
document.write(result.childNodes[0].nodeValue);
document.write("</strong>");
document.write("<br />");
result=nodes.iterateNext();
}
}
</script>

Getting a file from a server using Javascript

So, I wrote some JavaScript to grab an xml file from my desktop and display it on an html page. However, I now have added my xml file to a webserver (mongoose). I want to call the file from that server, but whenever I call the file from the server it dosen't work, but when I call it from my desktop it loads fine.
I want to swap
xmlhttp.open("GET","Devices.xml",false);
with
xmlhttp.open("GET","http://localhost:8080/Devices.xml",false);
Here is the code
<html>
<head>
<script type="text/javascript">
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","Devices.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// the <Device> list
x = xmlDoc.getElementsByTagName('Device');
// make a function that extracts the attributes out of a Node
function getDeviceAttributes(dvc) {
var name = dvc.getAttribute("name");
var uuid = dvc.getAttribute("uuid");
var id = dvc.getAttribute("id");
return "<p>name: " + name + "<br> uuid: " + uuid + "<br> id: "+ id + "</p>";
}
// loop through the list
// assuming order doesn’t matter
var txt = '';
for (var i = x.length; i--;) {
txt += getDeviceAttributes(x[i]);
}
//show the result on page load
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
</script>
</head>
<body>
<div id='showDevices'></div>
</body>
</html>
Does anyone know how I can get this to work?
I have been told to use AJAX and Jquery, but I have no idea how to or even where to begin.
It looks like you are repeating a lot of work that jQuery can do for you. Check out the documentation for the Get request method
So something like this:
$.get('http://localhost:8080/Devices.xml', function(data) {
$('#showDevices').html(data);
});
I believe that is the jQuery for what you are trying to do. Hope that helps.
-Charlie
Just some generic advice, you could also use the .load() ajax function if you didn't want to parse the response and this:
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
can be done in jQuery like this $("#showDevices").html(txt);

Categories

Resources