SCRIPT 600: Invalid target element for this operation. (IE Only) - javascript

I have a ajax calendar I am working on, it is working fine in Chrome, Safari & Firefox as usual. However It is not working in IE9 or below.
I am getting the following error SCRIPT 600: Invalid target element for this operation.
It is a WP plugin, but this is the code
function show_micro_ajax(response) {
document.getElementById('wp-calendar').innerHTML = response;
}
function microAjax(url, cF) {
this.bF = function(caller, object) {
return function() {
return caller.apply(object, new Array(object));
}
};
this.sC = function(object) {
if (this.r.readyState == 4) {
this.cF(this.r.responseText);
}
};
this.gR = function() {
if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else return false;
};
if (arguments[2]) this.pb = arguments[2];
else this.pb = "";
this.cF = cF;
this.url = url;
this.r = this.gR();
if (this.r) {
this.r.onreadystatechange = this.bF(this.sC, this);
if (this.pb != "") {
this.r.open("POST", url, true);
this.r.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
this.r.setRequestHeader('Connection', 'close');
} else {
this.r.open("GET", url, true);
}
this.r.send(this.pb);
}
}​

If you do not have to support IE6, remove the ActiveX line,
otherwise, reverse your test:
if (window.XMLHttpRequest) return new XMLHttpRequest();
else if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
else return false;
I'm not sure how the instance becomes an array here,
and possibly IE doesn't either, especially if one of the members in sn ActiveX object.
return caller.apply(object, new Array(object))

Related

How do i link a xml file with several nodes and subnodes?

am looking for a javascript that will load an xml file and will display something like rectangules with links based on the xml child nodes, parents linked to childs and subnodes linked to nodes. how would i be able to do this?
You can accomplish this with AJAX.
First, create a function that will pull information from your XML file:
function loadXMLdoc(url) {
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch(e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState === 4) {
if (ajaxRequest.status === 200) {
// a hidden div to display the result
var result = document.getElementById('result');
result.style.display = 'block';
result.innerHTML = ajaxRequest.responseText;
} else {
result.innerHTML = 'An error has occurred making the request';
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send();
};
}
From here, you can start grabbing data from your XML file. Inside your if (ajaxRequest.status === 200) { } statement, you can start calling elements:
var elem = ajaxRequest.responseXML.getElementById('elem');
var parents = elem.parentNodes;
var children = parents.childNodes;
It's up to you exactly how you'd like to format this and what data you're grabbing, but this should be a good starting point for you.

How to prevent Ajax caching

I'm created this class to fetch a file from web to check for new version using Ajax.
This code run on a Windows gadget, on IE8. But I'm having trouble because of the cache.
Is there a way to fix this Ajax class to disable cache?
PS: I don't use any library or frameworks.
var ClassAjax = function() {
this.data = null;
var that = this;
this.get = function(url, send) {
var ajax = new function ObjAjax() {
try{ return new XMLHttpRequest(); }
catch(e){try{ return new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e){ return new ActiveXObject("Microsoft.XMLHTTP"); }}
return null;
}
ajax.onreadystatechange = function() {
if(ajax.readyState == 1) { that.onLoading(); }
if(ajax.readyState == 4) { that.data=ajax.responseText; that.onCompleted(that.data); }
}
ajax.open("GET", url, true);
ajax.send(send);
};
this.onLoading = function() {
//function called when connection was opened
};
this.onCompleted = function(data) {
//function called when download was completed
};
}
var request = new ClassAjax();
request.onCompleted = function(data) { alert(data); }
request.get('http://exemple.com/lastversion.html', null);
You can pass the current timestamp as a variable in the url, like this :
var timestamp = new Date().getTime();
ajax.open("GET", url+'?ts='+timestamp, true);
Also, you can force the page to be reloaded on server-side, using the proper headers

Webpages on Firefox works well but no on IE

I have following code snippet:
self.xmlHttpReq = new XMLHttpRequest();
self.xmlHttpReq.onreadystatechange = function()
{
if(self.xmlHttpReq.readyState == 4 && self.xmlHttpReq.status == 200)
{
xmlDoc = self.xmlHttpReq.responseXML;
var xmlVar1 = xmlDoc.getElementsByTagName('var1')[0].childNodes[0].nodeValue;
var xmlVar2 = xmlDoc.getElementsByTagName('var2')[0].childNodes[0].nodeValue;
}
}
In IE the error code says:
object required, ajax request.js line num, char num
However, this same ajax request works fine in Firefox.
IE and Firefox have different object names for the XMLHttpRequest, you have to check your browser and declare the new object based on that.
Try something like this:
function getXHR() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xhr = false;
}
}
}
return xhr;
}
I got this from Jeremy Keith some time ago, it has never failed me.
Internet Explorer doesn't have the XMLHttpRequest object. Instead it uses an ActiveX object for the same functionality. So, you need to change this line:
self.xmlHttpReq = new XMLHttpRequest();
to:
if (window.ActiveXObject) {
try {
self.xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {
self.xmlHttpReq = new ActiveXObject('Msxml2.XMLHTTP'); // for really old versions of IE. You can leave the try/catch out if you don't care to support browsers from the '90s.
}
}
else
self.xmlHttpReq = new XMLHttpRequest();

XML ActiveXObject IE. Object doesn't support this action

I am trying to work with xml and javascript. In firefox it works great using XMLHttpRequest but in IE (6-8) I am getting the error:
Object doesn't support this action
I am using the following function:
function createRequestObject(){
var request;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
return request;
}
And then calling it with:
var xhttp = createRequestObject();
xhttp.open("GET","myfile.xml",false);
...
Any thoughts??
Try specifying a local variable for request, var request ( although it doesn't look like it should solve it ).
I would use this fn for light-weight XHR:
/** XHConn - Simple XMLHTTP Interface - bfults#gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
Usage:
var myConn = new XHConn();
if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
var fnWhenDone = function (oXML) { alert(oXML.responseText); };
myConn.connect("mypage.php", "POST", "foo=bar&baz=qux", fnWhenDone);
I think you need to put a var in front of request:
function createRequestObject(){
var request;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
return request;
}
IE often has problems with global variables.

AJAX responseXML errors

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;

Categories

Resources