XMLHttpRequest Only Working Locally with Firefox while loading an xml file - javascript

Hello I am new to the community. I would like to ask a question.
I am trying to create a template HTML5 for loading and doing quizzes. I have the xml file with the question and the answers and I am trying to load it, in my template.
The code I use is this:
To load the xml file
// The Script that loads the XML File Locally only works in Firefox for now
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
else {
xmlhttp = new XMLHttpRequest();
//Open the file using the GET routine
xmlhttp.open("GET", XMLname, false);
//Send request
xmlhttp.send(null);
//xmlDoc holds the document information now
return xmlDoc.responseXML;
}
alert("Error loading document!");
return null;
}​
To Pass the Contents to my HTML5 template
xmlDoc=loadXMLDoc("test"+file+".qxml");
My problem is that the data from the xmlfile are not retrieved. While on the server or on any other browser the xmlDoc variable appears as null.
Can you point me in some direction as I am new to the Javascript xmlhttprequest methods. Thanks a lot in advance for your time.
The file extension is not xml (it is .qxml). The problem is the extension of the file .qxml. So it there any way to bypass this and use my extension qxml instead of xml ?

Try to override the mime type returned by the server, and tell your browser that the data is XML.
// The Script that loads the XML File Locally only works in Firefox for now
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.overrideMimeType('text/xml');
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
else {
xmlhttp = new XMLHttpRequest();
//Open the file using the GET routine
xmlhttp.open("GET", XMLname, false);
xmlhttp.overrideMimeType('text/xml');
//Send request
xmlhttp.send(null);
//xmlDoc holds the document information now
return xmlDoc.responseXML;
}
alert("Error loading document!");
return null;
}​

Related

HowTo perform XSLT transform on XML from TextArea

I am struggling to perform an XSLT transform in the browser using just html and javascript (I have tried many different ways and none of them work). Here is what I want (and I just can't make it work).
1) I have an XSLT transform, I can make it available as a file (e.g. xslt), I can embed it in the HTML (I don't care), it is static.
2) I want the user to enter their XML into a text area.
3) I want the user to press a button and then I want the XSLT to occur and the result (which is html) to be displayed in a new tab.
Thanks for your help.
Finally got my own javascript to work. Here it is for anyone who needs it.
/**
* Load an XML document from server
*
* #param filename filename
*
* #return DOMDocument
*/
function loadXMLDoc(filename) {
if ((window.ActiveXObject) || (!(window.ActiveXObject) && "ActiveXObject" in window)) {
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {
xhttp.responseType = "msxml-document"
}
catch (err) { } // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
/**
* Text XML template: perform XSLT on user XML
*
*/
function testXMLTemplate() {
// create xml string from user xml in text area
var xmlstr = document.getElementById("test-xml").value;
xmlstr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlstr;
// load XSLT doc
var xsldoc = loadXMLDoc("xml/paramToHtml.xslt")
if ((window.ActiveXObject) || (!(window.ActiveXObject) && "ActiveXObject" in window)) {
// code for IE
var xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
xmldoc.async = false;
xmldoc.loadXML(xmlstr);
ex = xmldoc.transformNode(xsldoc);
var xmlTestWin = window.open();
xmlTestWin.document.write(ex);
}
else if (document.implementation && document.implementation.createDocument) {
// code for Chrome, Firefox, Opera, etc.
var xmlparser = new DOMParser();
var xmldoc = xmlparser.parseFromString(xmlstr, "text/xml");
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsldoc);
resultDocument = xsltProcessor.transformToDocument(xmldoc);
var xmlTestWin = window.open();
xmlTestWin.document.write(resultDocument.firstChild.innerHTML);
}
}

load an xml file using javascript i

i am trying to upload an xml file using javascript. my javascript code is given below:
var xmlDoc =null;
var abc = new Array();
if (window.ActiveXObject){
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation.createDocument){
xmlDoc=document.implementation.createDocument("","",null);
}
else{
alert('Browser cannot handle this script');
}
if (xmlDoc!=null){
xmlDoc.async=false;
xmlDoc.load("employee.xml");
var x = xmlDoc.getElementsByTagName("EMP");
for (i=0;i<x.length;i++)
{
abc[0] = x[0].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
document.write("a is "+abc[0]);
abc[1] = x[0].getElementsByTagName("ID1")[0].childNodes[0].nodeValue;
document.write("<br>b is "+abc[1]);
}
}
and my xml file is:
<EMPLOYEE>
<EMP>
<ID>10.99</ID>
<ID1>20.54</ID1>
</EMP>
</EMPLOYEE>
the code is working properly in IE as well as firefox but in Google Chrome, it is not showing anything. can some one tell me where i am wrong or how to correct it.
In order to get the XML file in Chrome you need to execute a GET. For security reasons you cannot load it in a straight forward manner from the file system. Here's code:
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", xmlsrc, false);
xmlhttp.send(null);
var xmlDoc = xmlhttp.responseXML.documentElement;

Can not load xml file in javascript

I am trying to load an xml file that is on my local system. But I always get Network_err. I do the following.
function LoadXmlDoc(dName)
{
var xhttp;
if(window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}
else
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
xhttp.open("GET", "file.xml", false);
xhttp.send();
}
catch(e)
{
window.alert("Unable to load the requested file.");
return;
}
return xhttp.responseXML;
}
How can I load an xml file that is on my system. all files are in same folder on my pc. Thanks
Try:
function XMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET","yourfile",true);
xmlhttp.send();
}
Updated due to simplify
Invoke XMLDoc() and pass your file uri instead of yourfile
Note: Don't forget to run this script on server
you might need to give proper path of xml file like this
xhttp.open("GET", "file:///C:/file.xml", false);
xhttp.send();
will do work fo ryou
full code will be like , Read more : Loading XML with Javascript
var xmlDoc;
var xmlloaded = false;
function initLibrary()
{
importXML("file:///C:/file.xml");
}
function importXML(xmlfile)
{
try
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlfile, false);
}
catch (Exception)
{
var ie = (typeof window.ActiveXObject != 'undefined');
if (ie)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
while(xmlDoc.readyState != 4) {};
xmlDoc.load(xmlfile);
readXML();
xmlloaded = true;
}
else
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = readXML;
xmlDoc.load(xmlfile);
xmlloaded = true;
}
}
if (!xmlloaded)
{
xmlhttp.setRequestHeader('Content-Type', 'text/xml')
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
readXML();
xmlloaded = true;
}
}
You can't using XHR due security reasons.
Check this post is very complete answer for you.
Then ckeck the HTML5 API for local files: http://www.html5rocks.com/en/tutorials/file/filesystem/

How to parse json from a url

I have a url contain all the json format.
http://api.musixmatch.com/ws/1.1/track.lyrics.get?apikey=d34fb59a16877bd1c540aa472491825b&track_id=12414632
function load() {
dashcode.setupParts();
var link = 'http://api.musixmatch.com/ws/1.1/track.search?apikey=d34fb59a16877bd1c540aa472491825b&q_track=back%20to%20december&page_size=10';
req.open = ("GET", link, false);
req.onreadystatechange = readXML();
req.send(null);
}
function readXML(){
alert(req.responseText);
}
this code keep saying null all the time.
Are there any way that i can retrieved those json text
The problem is with req.onreadystatechange = readXML();. You're assigning the result of the function instead of the function itself (as a callback).
You want req.onreadystatechange = readXML;. Though I must say I'm not sure how this code is supposed to work. Not in terms of how the XHR is made, nor with regards to the external domain.
Correct usage is as follows.You can check this link http://jsfiddle.net/UH4KY/1/ The link will alert undefined since cross domain scripting is not allowed .You can set the Access-Control-Allow-Origin and test the code.
function readXML(req) {
alert(req);
}
function load() {
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");
}
var link = 'http://api.musixmatch.com/ws/1.1/track.search?apikey=d34fb59a16877bd1c540aa472491825b&q_track=back%20to%20december&page_size=10';
//req.open = ("GET", link, false);
xmlhttp.onreadystatechange = function(){ alert(xmlhttp.responseText); }
xmlhttp.open("GET", link, false);
xmlhttp.send(null);
}

GetXmlHttpObject AJAX call to a php file

I am trying to call a php file using GetXmlHttpObject object and having some luck, but seem to have problem with the URL variable.
Is there something I have to do with the URL string differently?
Here is the relevant code:
remoteCounter('marks');//invoking function
document.write("<div id=\"marks\"></div>");//destination div
function GetXmlHttpObject () {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari, IE 7+
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer - old IE - prior to version 7
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function remoteCounter(param){
counterObj = GetXmlHttpObject();
var url="HTTP://dnsname/directory/view.php?" + param;
alert(url + " " + counterObj);
counterObj.open("GET", url , true);
counterObj.onreadystatechange=updateCounter;
counterObj.send(null);
}
function updateCounter(){
//alert('updateCounter');
if (counterObj.readyState == 4 || counterObj.readyState == "complete"){
document.getElementById("marks").innerHTML=counterObj.responseText;
}
}
I can replace the counterObj.responseText variable in document.getElementById("marks").innerHTML=counterObj.responseText;
and see the test string correctly in the source document, so I know the html and jscript source is not the problem.
I have commented out code in the view.php file to just echo a simple string, but that is not showing either - which again makes me think the problem is in the request to the file, not in the file, not in the source.
Actual server name and directory have been replaced by dnsname/directory for this post. Including alert for debugging.
thank you for assistance.
Replace order of two first lines:
document.write("<div id=\"marks\"></div>"); //destination div
remoteCounter('marks'); //invoking function
It's necesary declarate div tag with id "marks" first.

Categories