Read XML file using JavaScript in Chrome - javascript

I need to load and read an XML file using JavaScript.
The following code works fine in Firefox, IE and Opera:
function loadXMLDoc(dname) {
var xmlDoc
// Internet Explorer
try {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
}
catch (e) {
// Firefox, Opera, etc.
try {
xmlDoc = document.implementation.createDocument('', '', null)
}
catch (e) {
alert(e.message)
}
}
try {
xmlDoc.async = false
xmlDoc.load(dname)
return xmlDoc
}
catch (e) {
alert(e.message)
}
return null
}
But executing this code in Chrome gives me this error:
Object# has no method "load"

Legacy Code
document.implementation.createDocument does not work on Chrome and Safari.
Use XMLHttpRequest instead when possible:
function loadXMLSync(url) {
try {
// Prefer XMLHttpRequest when available
var xhr = new XMLHttpRequest()
xhr.open('GET', url, false)
xhr.setRequestHeader('Content-Type', 'text/xml')
xhr.send()
return xhr.responseXML
}
catch (e) {
// XMLHttpRequest not available, fallback on ActiveXObject
try {
var activex = new ActiveXObject('Microsoft.XMLDOM')
activex.async = false
activex.load(url)
return activex
}
catch (e) {
// Neither XMLHttpRequest or ActiveXObject are available
return undefined
}
}
}
Modern Browsers
If you're targeting modern browsers (> IE6), just use XMLHttpRequest:
function loadXMLSync(url) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url, false)
xhr.setRequestHeader('Content-Type', 'text/xml')
xhr.send()
return xhr.responseXML
}

On MDN, there is guidance to use XMLHttpRequest. But it isn't clear from DOMImplementation.createDocument until you drill into the return type and see that XMLDocument is not supported in Google Chrome. The example on W3Schools uses XMLHttpRequest.

follow this to print,load,append xml data.Here xml is stored as string inside javascript.This method works in chrome,firefox hopes it will work in others too
txt="<papers>"+"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<papers>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
x=xmlDoc.getElementsByTagName("paper");
for (var i = 0; i < x.length; i++) {
var athor =x[i].childNodes[0].firstChild.nodeValue;
var title = x[i].childNodes[1].firstChild.nodeValue;
var path = x[i].childNodes[2].firstChild.nodeValue;
var tack =x[i].childNodes[3].firstChild.nodeValue;
//do something with these values...
//each iteration gives one paper details
var xml=document.getElementById("element_id");//<div id="element_id"></div>
var li = document.createElement("br");// create a new <br>
newlink = document.createElement('A'); // creating an <a> element
newlink.innerHTML = athor;// adding <a>athor value here</a>
newlink.setAttribute('href', path);//
newlink.appendChild(li);// athor<br>
document.getElementById("element_id").appendChild(newlink);
//finaly it becomes <div id="element_id">athor<br></div>
}
i posted this answer here

Add
var xhr = new XMLHttpRequest();
xhr.open("GET", "/example/xdom/books.xml", false);
xhr.send(null);
xmlDoc = xhr.responseXML.documentElement;
return xmlDoc;
in catch statement. Like below:
function loadXMLDoc(dname) {
var xmlDoc
// Internet Explorer
try {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
}
catch (e) {
// Firefox, Opera, etc.
try {
xmlDoc = document.implementation.createDocument('', '', null)
}
catch (e) {
alert(e.message)
}
}
try {
xmlDoc.async = false
xmlDoc.load(dname)
return xmlDoc
}
catch (e) {
//alert(e.message)
// For Chrome
var xhr = new XMLHttpRequest();
xhr.open("GET", "/example/xdom/books.xml", false);
xhr.send(null);
xmlDoc = xhr.responseXML.documentElement;
return xmlDoc;
}
return null
}

Related

why my code doesn't work in chrome or FF

these 2 functions seems to be working only on IE. this is the code:
function onGridMembers(id,xml) {
if (xml != "<Members/>" && ToHelpOrNotToHelp) {
var domDoc = new ActiveXObject("Microsoft.XMLDOM");
domDoc.loadXML(xml);
var helpHtml2 = "";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "Dictionary.xml", true);
xmlDictionary = xmlhttp.responseXML;
xmlhttp.send();
helpHtml2 += xmlDictionary.selectSingleNode("Terms/Term[Key='" + domDoc.selectSingleNode("Members/Member/#UName").text + "']/Desc").text;
alert(helpHtml2);
}
}
function onCommandClicked(nectoId, commandId, commnadCaption, xml) {
if (commandId == "ID223") { // this one doesn't work in chrome
window.open('file://server/Guide.docx');
} else if (commandId == "ID225") { // This one works in chrome
window.open('http://server/Reports/Pages/Folder.aspx');
} else if (commandId == "ID227") { // this one doesn't work in chrome
getComponentById("vvv","ww").setMenuItemState("ID227", "Hidden");
getComponentById("vvv","ww").setMenuItemState("ID226", "Enable");
ToHelpOrNotToHelp = false;
} else if (commandId == "ID226") { // this one doesn't work in chrome
getComponentById("vvv","ww").setMenuItemState("ID226", "Hidden");
getComponentById("vvv","ww").setMenuItemState("ID227", "Enable");
ToHelpOrNotToHelp = true;
}
}
Can you please help?
I'm not sure about the second code, but the first cannot work in other browsers than IE because you're using ActiveX, which is MS-Only.
The Firefox Error-Console usually gives useful information on why JS is not working.

PUT/DELETE XMLHttpRequest Not Working in Firefox

I am working with javascript cross domain ajax request. my code is working fine on chrome and other devices like android browser and android native app using phonegap.
But i was facing issue with Firefox..
Firefox does not support my PUT and DELETE requests.
Is there any solution for firefox to make put and delete request to my server.
firefox does support my post and get request. both request working fine.
here is my working code.
var XMLHttpFactories = [
function () {
return new XMLHttpRequest()
},
function () {
return new ActiveXObject("Msxml2.XMLHTTP")
},
function () {
return new ActiveXObject("Msxml3.XMLHTTP")
},
function () {
return new ActiveXObject("Microsoft.XMLHTTP")
}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
For send Put request..
var xhr = createXMLHTTPObject();
xhr.open("PUT", url,true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
if(xhr.status==200){
request.success(xhr.responseText);
}else if(xhr.status!=200){
request.error(xhr.responseText)
}
}
}
xhr.send(body);
The following is working just fine on Firefox 22.0 (& 23.0 too):
var XMLHttpFactories = [
function () {
return new XMLHttpRequest()
},
function () {
return new ActiveXObject("Msxml2.XMLHTTP")
},
function () {
return new ActiveXObject("Msxml3.XMLHTTP")
},
function () {
return new ActiveXObject("Microsoft.XMLHTTP")
}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
var xhr = createXMLHTTPObject();
xhr.open("PUT", "/echo/html/", true);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
alert("Request completed, with the following status code: " + xhr.status);
}
xhr.send("");
Here is a jsFiddle: http://jsfiddle.net/qXQtD/
To better understand your situation, please answer the following:
What is the data you are trying to send?
What are your complete response headers (especially the "Access-Control-Allow-Origin" header)?

XMLHttpRequest.readyState

home.html
front page test
test.php
<SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
<button type="button" onclick="callAJAX('home.html','displaydiv')">Click Me!</button>
<div id="displaydiv"></div>
ajax.js
function callAJAX(url, pageElement, callMessage) {
document.getElementById(pageElement).innerHTML = callMessage;
try {
req = new XMLHttpRequest(); /* e.g. Firefox */
} catch(e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
/* some versions IE */
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
/* some versions IE */
} catch (E) {
req = false;
}
}
}
req.onreadystatechange = function() {responseAJAX(pageElement);};
req.open("GET",url,true);
req.send(null);
}
function responseAJAX(pageElement) {
console.log(req.readyState);
var output = '';
if (req.readyState == 4) {
if (req.status == 200) {
output = req.responseText;
document.getElementById(pageElement).innerHTML = output;
}
}
}
Above code is mainly from here:
Questions:
according to this site, onreadystatechange stores a function (or the name of a function) to be called automatically each time the readyState property changes so when will readyState property change? after req.send(null);?
for this line: console.log(req.readyState); in chrome console, it shows: 1 2 3 4, it does not output 0, is that because 0: request not initialized?
readyState changes in a few places, check out Mozilla's documentation for more information. req.readyState = 0 means that req.open() has not been called yet.
Also, depending on what browsers you are trying to support with this code, you can look into using some of the features from XHR2, including a req.onload() function that would change your code to:
function callAJAX(url, pageElement, callMessage) {
var elem = document.getElementById(pageElement);
elem.innerHTML = callMessage;
var req = new XMLHttpRequest();
req.onload = function() {
elem.innerHTML = req.responseText;
};
req.open("GET",url,true);
req.send(null);
}

how can i do jquery's $.get in pure javascript? (without wanting to return anything)

I want the mobile version of my site to be as snappy as possible, however i still want some basic analytics.
I want to ping a php file (hit counter) after the mobile page has loaded to count the amount of hits from javascript enabled browsers.
Jquery's a bit overkill for 1 ajax function so i'm keen to learn how to do the following in pure javascript:
<script type="text/javascript">
Window.onload(function(){
$.get('mvc/assets/ajax/analytics/event_increment.php?id='+id');
})
</script>
Create a utility function that will return to you a browser-specific Ajax object:
function ajax(url, method, callback, params = null) {
var obj;
try {
obj = new XMLHttpRequest();
} catch(e){
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function() {
if(obj.readyState == 4) {
callback(obj);
}
}
obj.open(method, url, true);
obj.send(params);
return obj;
}
You could then call that function like this:
var ajax = ajax('someurl', 'get', function(obj) { alert(obj.responseText); })
Just specify your file as the src attribute for the script tag.
Something simplistic:
<div id="hidden"></div>
<script type="text/javascript">
window.onload = function(){
var div = document.getElementById("hidden");
div.innerHTML = "<img src='tracking.php' />";
};
</script>
#Mike is suggesting a great method. If you would like to get into AJAX, though, it's not that difficult.
Code c/o bobince
var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();
// FOR <IE8 Compatibility do this first:
if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
window.XMLHttpRequest= function() {
return new ActiveXObject('MSXML2.XMLHttp');
};
}
replace x.html with your php file
While it is possible to create an image tag with that url as the src if you want to do it via AJAX as jQuery does there you could do this:
<script type="text/javascript">
function report(){
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",'mvc/assets/ajax/analytics/event_increment.php?id='+id',true);
}
window.onload = report;
</script>
You can use an img tag and put that in the src, and have your script return a transparent image.
Or as someone else pointed out, have it be the src of a script tag.
EDIT
If you don't want it to load if a bot accesses the page, you could use an img tag still
<img src="transparent.gif" width="1" height="1" />
Then, use javascript to change the src of the image to your php script. Most bots won't execute the javascript and therefor will never access your php script.
You may want to obfuscate the javascript a little though, so they don't see a url in it and try and access it.
<script type="text/javascript">
Window.onload(function(){
var id = "", xmlhttp = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.open("GET","mvc/assets/ajax/analytics/event_increment.php?id=" + id,true);
xmlhttp.send();
}
})
</script>
there existed image preloaders in the early days of webpages, when internet connections were still slow, which created image objects to be used for rollover effects. this should still work and load the image:
<script type="text/javascript">
var img = new Image('http://url.to/your/image/or/script');
</script>
As 2019 you can use ES6 fetch a modern replacement for XMLHttpRequest.
const options = {
method: "POST",
data: {
title: "foo",
body: "bar",
userId: 1
},
credentials: "include",
headers: {}
};
fetch("https://jsonplaceholder.typicode.com/posts", options)
.then(response => {
return response.json();
})
.then(jsonObject => {
console.log(jsonObject);
document.write(`ID ${jsonObject.id} was created!`);
})
.catch(error => {
document.write(error);
});

Dynamically change a div's ID?

I have a bunch of divs with weird id and each of them contains a video. They're actually video embed codes but they're not usual to me. Here's one example:
<div id="evp-1fae4e37639894816f03591bc7009c68-wrap" class="evp-video-wrap"></div><script type="text/javascript" src="http://domain.com/evp/framework.php?div_id=evp-1fae4e37639894816f03591bc7009c68&id=cmVsYXRpb25zaGlwLW1hcmtldGluZy0xLmZsdg%3D%3D&v=1278525356"></script><script type="text/javascript">_evpInit('cmVsYXRpb25zaGlwLW1hcmtldGluZy0xLmZsdg==');</script>
What I want to do is create a video playlist. As a part of that, I created list using divs also which use the onclick attribute to trigger my JS function to switch between videos. Here's how it looks:
<div class="vid-list" onclick="switchvideo('http://domain.com/html-vids/headline-vids/second-vid.html', 2)"><p>This a video tutorial for blah blah blah.</p></div>
The problem is, each time I switch to another video the div id of the embed code changes also because otherwise it won't work. So I need to change that before loading the video script inside the div. I tried to achieve that using the following JS function:
function switchvideo(url, vidnumber)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",url,false);
xmlhttp.send();
}
var div_node = document.getElementByClass('evp-video-wrap');
if ( vidnumber == 2 ) {
div_node.id = 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap';
}
document.getElementById(div_node.id).innerHTML=xmlhttp.responseText;
}
Apparently it's not working. I suspect the problem are the lines in bold above. I tried to get the element by 'class' and its id by using 'div_node.id'. I am assuming that by doing 'document.getElementByClass', I am getting the reference to that element so I could use it to manipulate its other attributes. But I am not sure... Could anyone pls enlighten me??
There is no getElementByClass() method. There is a getElementByClassName() but it's not available in every browser.
Here is one you can use:
// http://www.dustindiaz.com/getelementsbyclass/
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null) node = document;
if (tag == null) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Then you can call it as
getElementByClass('evp-video-wrap');
Your ajax is a bit tricky, but here is a more general one:
function getXmlHttpObject() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xmlHttp) {
alert("Your browser does not support AJAX!");
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function() {
if (this.readyState === 4) {
// onSuccess
if (this.status === 200 && typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
// onError
else if(typeof onError == 'function') {
onError();
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}
Finally your code becomes:
function switchvideo(url, vidnumber) {
var div_node = getElementByClass('evp-video-wrap')[0];
// make a call to the url, and execute the
// callback when the response is available
ajax(url, function( responseText ){
if (vidnumber == 2) {
div_node.id = 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap';
}
document.getElementById(div_node.id).innerHTML = responseText;
});
}​
You can see the whole code [here]
getElementByClass isn't a standard method. Is it possible for you to use a framework for this? jQuery has a nice mechanism to search for an element by class, as do the other frameworks. It also makes it much easier to do the AJAX bits in a cross-browser supported way.
function switchvideo(url, vidnumber)
{
$.get(url, function(data) {
var div_node = $('.evp-video-wrap');
if (vidnumber == 2) {
div_node.attr('id', 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap');
}
div_node.html( data );
});
}
An alternative would be to write your own getElementByClass or specific code to search for a DIV by class. Note: I assume you're only interested in the first match.
function getDivByClass( klass )
{
var regex = new RegExp( '(^|\\s+)' + klass + '(\\s+|$)' );
for (div in document.getElementsByTagName('div')) {
if (regex.text( div.className)) {
return div;
}
}
return null;
}

Categories

Resources