We have a web application that makes use of native XMLHttpRequest() to send data back to our server. One of our larger clients have users that appear to be running IE8 in Win7 (64-bit) and have "Enable native XMLHTTP support" disabled in their browser.
We've implemented the typical scenario of instantiating an ActiveXObject in place of XMLHttpRequest in order to try to support the likes if IE6 (no native XMLHTTP support; yes, we still have clients running this on thin clients!) which I am hoping IE8 can utilise as a fallback if this checkbox option has been switched off. However, once an object has been created, I get a type error when calling open() method on it.
Here's my code:
// Posts back an xml file synchronously and checks for parse error.
// Returns xml object or null. Used in RSUserData.
XML.PostXmlFile = function(sURL, doc)
{
try
{
// Validate Input
if ((typeof (sURL) != "string") || (sURL == ""))
return null;
if (window.XMLHttpRequest) // IE7+, FF and Chrome
{
// Mozilla, create a new DOMParser and parse from string
// Although IE9 and IE10 can successfully load XML using this block, it can't use document.evaluate nor selectNodes/selectSingleNode to navigate it
// Ref: http://msdn.microsoft.com/en-us/library/ie/ms535874(v=vs.85).aspx
// Ref: http://msdn.microsoft.com/en-us/library/ie/ms534370(v=vs.85).aspx
// Ref: http://blogs.msdn.com/b/ie/archive/2012/07/19/xmlhttprequest-responsexml-in-ie10-release-preview.aspx
var req = new XMLHttpRequest();
req.open("post", sURL, false);
req.send(doc);
if (req.status != 200)
throw { message: 'HTTP Post returned status ' + req.status + ' (' + req.statusText + ') when sending to ' + sURL };
// IE11+: req.responseXML returns a native XML Document
// IE9/10: req.responseXML returns an IXMLDOMDocument2 object but we can convert req.responseText to native XML using DOMParser
// IE6/7/8: req.responseXML returns an IXMLDOMDocument2 object but DOMParser is not available
if (window.DOMParser)
{
var parser = new DOMParser();
return parser.parseFromString(req.responseText, 'application/xml');
}
else
return req.responseXML; // NATIVE
}
else
{
// up to IE6:
// Ref: http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
var oXML = XML.GetActiveX_XML();
if (!oXML)
throw { message: "Could not instantiate an Msxml2 ActiveXObject", innerException: e };
oXML.open('POST', sURL, true);
oXML.send(sFile);
if (oXML.parseError.errorCode == 0)
{
xmlDoc = oXML;
return xmlDoc;
}
return null;
}
}
catch (e)
{
var s = "Exception in XML.PostXmlFile(). " + (e.message ? e.message : "");
throw { message: s, innerException: e };
}
}
XML.GetActiveX_XML = function()
{
var progIDs = ['Msxml2.DOMDocument.6.0', 'Msxml2.DOMDocument.3.0'];
for (var i = 0; i < progIDs.length; i++)
{
try
{
var oXML = new ActiveXObject(progIDs[i]);
var sl = oXML.getProperty("SelectionLanguage");
if (sl !== "XPath")
oXML.setProperty("SelectionLanguage", "XPath"); // Changes v3.0 from XSLPattern to XPath
var ns = "xmlns:rs='" + XML._nsResolver('rs') + "' xmlns:xsi='" + XML._nsResolver('xsi') + "'";
// ns = "xmlns:na='http://myserver.com' xmlns:nb='http://yourserver.com'";
oXML.setProperty("SelectionNamespaces", ns);
return oXML;
}
catch (ex) { }
}
return null;
}
NOTES:
The aim is to call to XML.PostXmlFile() with the url and payload.
Modern browsers use new XMLHttpRequest() as expected
IE6 is expected to use XML.GetActiveX_XML() on account that window.XMLHttpRequest returns falsey
IE8 with "Enable native XMLHTTP support" disabled falls through to the IE6 code (because window.XMLHttpRequest returns falsey) but the instantiated object fails because it doesn't support open() method (oXML.open('POST', sURL, true);)
Is there any way I can post my payload back using IE8 when "Enable native XMLHTTP support" is disabled?
You should see if the Microsoft.XMLHTTP is available before checking if there is a XMLHttpRequest:
var bActiveX;
try {
new ActiveXObject('Microsoft.XMLHTTP');
bActiveX = true;
}
catch(e) {
bActiveX = false;
}
And then, check in your if condition:
if (window.XMLHttpRequest || bActiveX) { // IE7+, FF and Chrome
var req = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
/* the rest of your code */
}
I am trying to do native javascript and requesting an html page using the following JS code, why does it return (in Chrome) the following?
XMLHttpRequest cannot load /live-examples/temp.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
The code I am using is as follows:
var sendRequest = (function(){
// Private member variables
var readyState = {
UNSENT : 0,
OPENED : 1,
HEADERS_RECIVED : 2,
LOADING : 3,
DONE : 4
}
var status = {
SUCCESS : 200,
NOT_MODIFIED : 304
}
// Private member methods
function getData(callBack){
var xhr = getXhr();
if(!xhr){
console.log('unable to create xhr object.')
return false;
}
// test readyState
if(xhr.readyState !== readyState.DONE) return;
if(xhr.status === status.SUCCESS && xhr.status !== status.NOT_MODIFIED){
callBack(xhr.responseText);
}
}
function getXhr(){
var XMLHttpList = [
function(){ return new XMLHttpRequest(); },
function(){ return ActiveXObject("Msxml2.XMLHTTP"); },
function(){ return ActiveXObject("Microsoft.XMLHTTP"); }
], xhr;
for(var i = 0; i < XMLHttpList.length; i++){
try{
xhr = XMLHttpList[i];
break;
}catch(e){
continue;
}
}
return xhr();
}
return function(url, callBack, postData){
var xhr = getXhr();
if(!xhr) return;
var method = (postData) ? 'POST' : 'GET';
xhr.open(method, url, true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.onreadystatechange = getData(callBack);
xhr.send(postData);
};
})();
function dealWithResponse(response){
// the response from the xhr request
console.log('success response: ' + response);
}
// cross origin request error.
$(function(){
document.getElementById('MyID').onclick = function(){ sendRequest('/live-examples/temp.html', dealWithResponse, 'GET'); }
});
HTML code within the BODY is as follows:
<button id="MyID">I have a button!</button>
I checked the the file 'temp.html' does exist.
I am in this code just trying to show some simple ajax call using native javascript in a talk I am due to present.
Many thanks in Advance,
Quinton :)
You need to use HTTP when you want to access data using the XMLHTTPRequest object.
This is the code I wrote:
function responseAjax(element, url, loader, data) {
if(request.readyState == 4) {
if(request.status == 200) {
//The response has 2 main parts: the main page element and the javascript that have the text "???PHPTOSCRIPT???" in between
output = request.responseText.split('???PHPTOSCRIPT???');
if (element) document.getElementById(element).innerHTML = output[0];//put first part into element
if (output[1] != "") eval(output[1]); //execute script
//remember the last request
if (typeof(url) !== 'undefined') {
document.cookie = "requestedURL=" + escape(url);
document.cookie = "requestedElement=" + escape(element);
document.cookie = "requestedLoader=" + escape(loader);
document.cookie = "requestedData=" + escape(data);
};
};
};
};
function ajax(url, element, loader, data, remember, async) {
remember = (typeof(remember) === 'undefined') ? false : remember;//remember last request. Default: false
async = (typeof(async) === 'undefined') ? true : async;//handle request asynchronously if true. Default: true
if (loader) document.getElementById(element).innerHTML = loader;
try { request = new XMLHttpRequest(); /* e.g. Firefox */}
catch(err) {
try { request = new ActiveXObject("Msxml2.XMLHTTP"); /* some versions IE */}
catch(err) {
try { request = new ActiveXObject("Microsoft.XMLHTTP"); /* some versions IE */}
catch(err) { request = false;}
}
}
if (request) {
url += "?r=" + parseInt(Math.random()*999999999);//handle the cache problem
//put an array of data into string. Default: null array
data = data || [];
for (var i = 0; i < data.length; i++) {
url += "&" + data[i];
};
request.open("GET", encodeURI(url), async);
url = url.split('?');//get query string for remembered request
request.onreadystatechange = (remember) ? function() {responseAjax(element, url[0], loader, data.join('&'));}
: function() {responseAjax(element)};
request.send(null);
} else {
document.getElementById(element).innerHTML = "<h3>Browser Error</h3>";
};
};
Though I use eval() to handle returned script, the script doesn't work on events after all if I use pure javascript. However, if I use jQuery such as $("#tab-panel").createTabs();, this code works fine.
Can someone please explain why pure javascript on the loaded content of ajax doesn't work?
Additional information: As I said, pure javascipt such as function sent through the ajax content doesn't work on events, however another code such as alert() works fine.
My code looks like this, which is recommended for IE to work, but it only works in Chrome and FF. Is there a correct way to access a url from another domain. Furthermore, the domain is a domain I own and can allow access to the scripts trying to access it:
<script language="javascript" type="text/javascript">
function sendRequest(url,callback,postData) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
// alert('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
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;
}
function handleRequest(req) {
var MyResponse = req.responseText;
document.open();
document.write(MyResponse);
document.close();
}
sendRequest("http://anotherdomain.com/urlwithcontentneeded.php",handleRequest);
</script>
IE does not suppoort cross domain requests in this way but does have a way using the XDomainRequest object instead, see http://msdn.microsoft.com/en-us/library/cc288060(v=vs.85).aspx
It works in much the same way though, and yes it's a pain there are two ways to do it in different browsers
I've been having some weird issues when it comes to make an AJAX request and handling the response.
I am making an ajax call for an xml file. however when i get the response the xhr.responseText property works fine in firefox but not in IE.
Another thing is that I am trying to access the xhr.responseXML as XMLDocument, but it tells me in firefox it tells me that xhr.responseXML is undefined in ie it doesnt even show me the undefined error or displays the output.
This is the code I am using to make the request:
var ajaxReq = function(url, callback) {
//initialize the xhr object and settings
var xhr = window.ActiveXObject ?
new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(),
//set the successful connection function
httpSuccess = function(xhr) {
try {
// IE error sometimes returns 1223 when it should be 204
// so treat it as success, see XMLHTTPRequest #1450
// this code is taken from the jQuery library with some modification.
return !xhr.status && xhr.status == 0 ||
(xhr.status >= 200 && xhr.status < 300) ||
xhr.status == 304 || xhr.status == 1223;
} catch (e) { }
return false;
};
//making sure the request is created
if (!xhr) {
return 404; // Not Found
}
//setting the function that is going to be called after the request is made
xhr.onreadystatechange = function() {
if (!httpSuccess(xhr)) {
return 503; //Service Unavailable
}
if (xhr.responseXML != null && xhr.responseText != null &&
xhr.responseXML != undefined && xhr.responseText != undefined) {
callback(xhr);
}
};
//open request call
xhr.open('GET', url, true);
//setup the headers
try {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "text/xml, application/xml, text/plain");
} catch ( ex ) {
window.alert('error' + ex.toString());
}
//send the request
try {
xhr.send('');
} catch (e) {
return 400; //bad request
}
return xhr;
};
and this is how i am calling the function to test for results:
window.onload = function() {
ajaxReq('ConferenceRoomSchedules.xml', function(xhr) {
//in firefox this line works fine,
//but in ie it doesnt not even showing an error
window.document.getElementById('schedule').innerHTML = xhr.responseText;
//firefox says ''xhr.responseXML is undefined'.
//and ie doesn't even show error or even alerts it.
window.alert(xhr.reponseXML.documentElement.nodeName);
});
}
This is also my first attempt to work with AJAX so there might be something that I am not looking at right.
I've been searching crazy for any indications of why or how to fix it, but no luck there.
any ideas would be great.
EDIT:
I know this would be better with a framework, but the boss doesn't want to add a framework for just an ajax functionality ('just' is not a fair word for ajax :P). So I am doing it with pure javascript.
The XML file is well-formed, I see it well in the web browser, but for completion this is the testing file I am using:
<?xml version="1.0" encoding="utf-8"?>
<rooms>
<room id="Blue_Room">
<administrator>somebody#department</administrator>
<schedule>
<event>
<requester>
<name>Johnny Bravo</name>
<email>jbravo#department</email>
</requester>
<date>2009/09/03</date>
<start_time>11:00:00 GMT-0600</start_time>
<end_time>12:00:00 GMT-0600</end_time>
</event>
</schedule>
</room>
<room id="Red_Room">
<administrator>somebody#department</administrator>
<schedule>
</schedule>
</room>
<room id="Yellow_Room">
<administrator>somebody#department</administrator>
<schedule>
</schedule>
</room>
</rooms>
EDIT 2:
Well the good news is that I convinced my boss to use jQuery, the bad news is that AJAX still perplexes me. I'll read more about it just for curiousity. Thanks for the tips and I gave the answer credit to Heat Miser because he was the closest working tip.
I was having the same problem a few years ago, then I gave up on responseXML and began always using responseText. This parsing function has always worked for me:
function parseXml(xmlText){
try{
var text = xmlText;
//text = replaceAll(text,"<","<");
//text = replaceAll(text,">",">");
//text = replaceAll(text,""","\"");
//alert(text);
//var myWin = window.open('','win','resize=yes,scrollbars=yes');
//myWin.document.getElementsByTagName('body')[0].innerHTML = text;
if (typeof DOMParser != "undefined") {
// Mozilla, Firefox, and related browsers
var parser=new DOMParser();
var doc=parser.parseFromString(text,"text/xml");
//alert(text);
return doc;
}else if (typeof ActiveXObject != "undefined") {
// Internet Explorer.
var doc = new ActiveXObject("Microsoft.XMLDOM"); // Create an empty document
doc.loadXML(text); // Parse text into it
return doc; // Return it
}else{
// As a last resort, try loading the document from a data: URL
// This is supposed to work in Safari. Thanks to Manos Batsis and
// his Sarissa library (sarissa.sourceforge.net) for this technique.
var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text);
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
return request.responseXML;
}
}catch(err){
alert("There was a problem parsing the xml:\n" + err.message);
}
}
With this XMLHttpRequest Object:
// The XMLHttpRequest class object
debug = false;
function Request (url,oFunction,type) {
this.funct = "";
// this.req = "";
this.url = url;
this.oFunction = oFunction;
this.type = type;
this.doXmlhttp = doXmlhttp;
this.loadXMLDoc = loadXMLDoc;
}
function doXmlhttp() {
//var funct = "";
if (this.type == 'text') {
this.funct = this.oFunction + '(req.responseText)';
} else {
this.funct = this.oFunction + '(req.responseXML)';
}
this.loadXMLDoc();
return false;
}
function loadXMLDoc() {
//alert(url);
var functionA = this.funct;
var req;
req = false;
function processReqChange() {
// alert('reqChange is being called');
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
eval(functionA);
if(debug){
var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes');
debugWin.document.body.innerHTML = req.responseText;
}
} else {
alert("There was a problem retrieving the data:\n" +
req.statusText + '\nstatus: ' + req.status);
if(debug){
var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes');
debugWin.document.body.innerHTML = req.responseText;
}
}
}
}
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processReqChange;
if(this.url.length > 2000){
var urlSpl = this.url.split('?');
req.open("POST",urlSpl[0],true);
req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
req.send(urlSpl[1]);
} else {
req.open("GET", this.url, true);
req.send("");
}
}
}
function browserSniffer(){
if(navigator.userAgent.toLowerCase().indexOf("msie") != -1){
if(navigator.userAgent.toLowerCase().indexOf("6")){
return 8;
}else{
return 1;
}
}
if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1){
return 2;
}
if(navigator.userAgent.toLowerCase().indexOf("opera") != -1){
return 3;
}
if(navigator.userAgent.toLowerCase().indexOf("safari") != -1){
return 4;
}
return 5;
}
Granted, this is very old code, but it is still working for me on a site I built a few years ago. I agree with everyone else though I typically use a framework nowadays so I don't have to use this code or anything like it anymore.
You can ignore some of the particulars with the split, etc... in the Request onreadystate function. It was supposed to convert the request to a post if it was longer than a certain length, but I just decided it was always better to do a post.
This problem occurs mostly when content type is mis-detected by the browser or it's not sent correctly.
Its easier to just override it:
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.overrideMimeType("text/xml");
request.send(null);
return request.responseXML;
Not sure why... This problem occurs only with Safari and Chrome (WebKit browsers, the server sends the headers correctly).
Are you calling the URL relative to the current document? Since IE would be using the ActiveXObject, it might need an absolute path, for example:
http://some.url/ConferenceRoomSchedules.xml
As for the XML, are you sure it's well-formed? Does it load in an XML editor, for instance?
What I can suggest you is to take a look at frameworks that hide and manage these cross-browser issues for you (in a reliable way). A good point here is jQuery. Doing these things yourself can become quite difficult and complex.
This may be what you need.
//Edit:
This is how the w3school shows it:
function ajaxFunction()
{
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!");
}
}
To avoid your cross browser problems (and save yourself coding a lot of items that a strong community has already developed, tested, and reviewed), you should select a javascript library. JQuery and Dojo are great choices.
I believe that your web server need to serve correct response headers with 'ConferenceRoomSchedules.xml' e.g. Content-Type: text/xml or any other xml type.
The answer provided by Aron in https://stackoverflow.com/a/2081466/657416 is from my point of view the simplest (and the best) one. Here is my working code:
ajax = ajaxRequest();
ajax.overrideMimeType("text/xml");
ajax.open("GET", myurl;