DOMParser.parseFromString fails with XML5619: Incorrect document syntax - javascript

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/

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?

Read text file on server into array javascript

Here's the situation. On the apache box there's a text file that contains numbers with new lines:
eg:
25
34
76
etc....
What I'm wanting to do it grab the values from that file and use them to "set" some sliders I have which are partially yoinked from http://webfx.eae.net/dhtml/slider/slider.html
Once done I'll have a "commit" button which writes out the altered values to that text file.
But I'm getting stuck at the bit where you read from the text file on the apache box which this runs in.
Everything I've read seems to refer to file uploading via an API but this isn't what i want as the file is server side.
I guess I could use php but as I'm not up on that either (and especially not on how to move variables between the two)
Any ideas? If you need clarification i can give it to you.
Just a simple ajax code!!!
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("mytextfiledic").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mytextfile.txt",true);
xmlhttp.send();
You can use the XMLHttpRequest :
var xhr = new XMLHttpRequest();
xhr.open( 'GET', 'foobar.txt', true );
xhr.onreadystatechange = function() {
if( xhr.readyState == 4 ) {
if( xhr.status >= 200 && xhr.status<300 || xhr.status == 304 ) {
//your text file is downloaded into xhr.responseText
console.log( xhr.responseText.split('\n') );// there you have your array.
}
}
}
xhr.send();

Reading XML from URL using 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>

Questions to create a nested list retrieved from an XML-file and displayed in xHTML

The objective is to display a list of URLs in an HTML page. The list is retrieved from another file (currently in XML-format).
Validator: What is the proper xHTML mark-up for a list generated by JavaScript and still validate properly?
I assume the reason is that JavaScript-code inside [ul]'s is not accepted. Is this correct? Is there another solution?
The code below does produce the list anticipated, but it creates a warning (pls see below, 2.).
<ul>list A
<li>item A1</li>
<li>item A2</li>
<ul>List B
<li>item B1</li>
<script type="text/javascript">/* <![CDATA[ */
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.open("GET","/test-code/panorama-list2.xml",false);
// xmlhttp.open("GET","/test-code/panorama-list2.xml",true); //this does not work. xmlDoc is null.
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{ document.write('<li class="menu2">'+'<a href="');
document.write(x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue);
document.write('">');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('</li>'); }
//]]></script> //This is line: 136
</ul>
The JavaScript used in the code above is called using the synchronous method and thus creating the Warning:
"An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
/ Source File: /test-code/index2.htm / Line: 136"
The solution is to use the asynchronous method similar to the code below placed into the section.
The solution is NOT to simply setting 'true' in the function xmlhttp.open (..., ..., true);.
<script type="text/javascript">//<![CDATA[
function loadXMLDoc()
{
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)
xmlDoc = xmlhttp.responseXML;
var txt = "";
var txt1 = "";
var x = xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
txt = x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue + "<br />";
txt1 = x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue + "<br />";
}
{
document.getElementById("myDiv").innerHTML=txt;
document.getElementById("myDiv1").innerHTML=txt1;
}
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
//]]></script>
That does take care of the Warning.
I assume a solution would be to combine these 2 examples of code.
That's what I am trying:
The Variables 'txt' and 'txt1' retrieve the last entry of the XML-file.
How do I get all entires as well? The amount of entries varies.
Here is the big question:
How can I create a proper list using the asynchronous method and obtain a result like in the initial code example where the list is generated by stepping through the XML-file?
After all, is there is another, better or simpler solution? The file with data for the list shall not be part of the xHTML mark-up.
At last an actual page using the initial code example. The list is revealed by hovering over the button at top-right: http://www.halo-photographs.com/2011-Cascata-da-Bernina/index.htm (yes, this is my own page)
Thanks for your attention.
you code is an soup..
you need refactor that
now with jquery
in the load the you page
you should put somthing how that
$(document).ready(function(){
BeforePrepareList();
});
function BeforePrepareList()
{
var xmlRequest = XmlHttpRequestResolver();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
var xmlDoc = xmlhttp.responseXML;
// you need parse string response a array or use xslt, the next
// is simple for each
ListSetting(xmlDoc);
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
function XmlHttpRequestResolver()
{
if (window.XMLHttpRequest)
return xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
function ListSetting(rawdata)
{
ListPopulate($("_PUT_YOUR_LIST_ID_HERE").get(0), rawdata);
}
function ListPopulate(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('All', '');
// THAT IS AN SIMPLE EXAMPLE, CHANGE FOR CREATE tag <a />
$.each(items, function (index,item) {
el.options[el.options.length] = new Option(item.[PROPERTY_A], item.[PROPERTY_B]);
});
}
and .....
more information here
invoke xml and transform http://www.ibm.com/developerworks/xml/library/x-ffox3/index.html
examples de http request http://www.jibbering.com/2002/4/httprequest.html

How to parse HTML from JavaScript in Firefox?(2)

Im trying to parse a HTML result of **XmlHttpRequest** in Firefox. Im expecting to receive the HTML result from XmlHttpRequests *responseText* but when Im calling an alert(responseText) nothing is displayed.
Ive followed the example from http://stackoverflow.com/questions/888875/how-to-parse-html-from-javascript-in-firefox but that doesnt work either.
Here is thecode to make myself clear:
<html>
<head>
<script type="text/javascript">
var http1;
var result;
function onPageLoad()
{
http1=getXmlHttpObject();
http1.open("GET", "https://login.yahoo.com/config/login_verify2?&.src=ym", true);
http1.send(null);
http1.onReadyStateChange=stateChanged();
}
function stateChanged()
{
if(http1.readyState==4)
{
result = http1.responseText;
alert("result"+ result);
var tempDiv = document.createElement('div');
tempDiv.innerHTML = result.replace(/<script(.|\s)*?\/script>/g, '');
// tempDiv now has a DOM structure:
alert(tempDiv.getElementById('username').size);
}
else
alert("mircea geoana la zoo");
}
function getXmlHttpObject()
{
var objXMLHttp=null;
if (typeof XMLHttpRequest!= 'undefined')
{
objXMLHttp=new XMLHttpRequest();
}
else
{
objXMLHttp=new ActiveXObject(Microsoft.XmlHttp);
}
return objXMLHttp;
}
</script>
</head>
<body onload="onPageLoad()">
<p>aaa<p>
</body>
</html>
http1.onReadyStateChange=stateChanged();
should be
http1.onReadyStateChange=stateChanged;
I see a big mistake there.. the message on the else branch should read 'miRcea', not 'micea'.. Tell me if this solves your issue, Mr claudiu ;))
this is how you should define the xmlhttp Object:
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
Check out this w3School tutorial to read about how to properly use AJAX calls and the like.
edit - my bad, only saw the line defining the call for IE6/5. Either way this method is much more clean.
You can only send AJAX requests to the same domain from which the JavaScript originates. And I'm guessing you're not sending your requests from "login.yahoo.com"...

Categories

Resources