The XMLHttpRequestObject does not seem to work on IE 6 or 7

E

eholz1

Hello JavaScript group,

I am trying to use/learn something about using AJAX (aka JavaScript)
for web pages, etc.
I am trying to use code out of "Ajax Web Applications" by Matthew
Eernisse.

This is just a simple affair using two html pages (ajaxtest.html and
ajaxmonitor.html).

It the case of ajaxtest.html all it does is flash a window.alert on
the screen with the word "OK".

The ajaxmonitor.html polls the server and has a little timing loop.
Both of these pages work in Firefox and Safari. Needless to say IE 6
and 7 i see no results. This is on several different computers (PCs).

I have searched around, but have had no luck it getting this code to
play on IE.

I am sure I am missing something. I have an external java script file
(ajax.js) which is supposed to create an XMLHttpRequestObject class,
with some methods, properties, etc. The html page merely instantiates
the "object" and accesses methods, etc.

I will attach my ajax.js file and the ajaxtest.html code. Would you
please be so kind as to point me in the right direction so this will
work in IE as well????

Code:
*****************************************************************************
ajax.js

function Ajax() {
this.req = null;
this.url = null;
this.method = 'GET';
this.async = true;
this.status = null;
this.statusText = '';
this.postData = null;
this.readyState = null;
this.responseText = null;
this.responseXML = null;
this.handleResp = null;
this.responseFormat = 'text'; //'text', 'xml', or 'object'
this.mimeType = null;

//test function for script...
this.sayHello = function() {
this.message = 'Hello Tester!';
window.alert(this.message);
};

//init method
this.init = function() {
if (!this.req) {
try {
//try to create object for Firefox, Safari, IE7, etc.
this.req = new XMLHttpRequest();
}
catch (e) {
try {
//try to create object for later verisons of IE.
//this.req = new ActiveXObject('MSXML2.XMLHTTP');
this.req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (e) {
try {
//try to create object for later verisons of IE.
this.req = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {
//could not create an HTTPRequest Object
window.alert("cannot create object");
return false;
}
}
}
}
return this.req;
};


/* good this.init = function() {
var i = 0;
var reqTry = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP') },
function() { return new ActiveXObject('Microsoft.XMLHTTP' )} ];

while (!this.req && (i < reqTry.length)) {
try {
this.req = reqTry[i++]();
}
catch(e) {}
}
return true;
};*/

// send a request method
this.doReq = function() {
if (!this.init()) {
alert('Could not create XMLHttpRequest object.');
return;
}
this.req.open(this.method, this.url, this.async);

if (this.mimeType) {
try {
req.overrideMimeType(this.mimeType);
}
catch (e) {
// could not override mime type -- IE 6 or Opera
}
}
var self = this; //fixes the loss-of-scope in inner function
this.req.onreadystatechange = function() {
var resp = null;
if (self.req.readyState == 4) {
//Do Stuff Here
switch (self.responseFormat) {
case 'text':
resp = self.req.responseText;
break;
case 'xml':
resp = self.responseXML;
break;
case 'object':
resp = req;
break;
}
if (self.req.status >= 200 && self.req.status <= 299) {
self.handleResp(resp);
}
else {
self.handleErr(resp);
}
}
};
this.req.send(this.postData);
};

// set mime type method
this.setMimeType = function(mimeType) {
this.mimeType = mimeType;
};

// error handler
this.handleErr = function() {
var errorWin;
try {
errorWin = window.open('', 'errorWin');
errorWin.document.body.innerHTML = this.responseText;
}
catch (e) {
alert('An error occurred, but the error message cannot be '
+ 'displayed. This is probably because of your browser\'s '
+ 'pop-up blocker.\n'
+ '\n'
+ 'Status Code: ' + this.req.status + '\n'
+ 'Status Description: ' + this.req.statusText);
}
};

// set error handle methods
this.setHandlerErr = function(funcRef) {
this.handleErr = funcRef;
};

this.setHandlerBoth = function(funcRef) {
this.handleResp = funcRef;
this.handleErr = funcRef;
};

this.abort = function() {
if (this.req) {
this.req.onreadystatechange = function() { };
this.req.abort();
this.req = null;
}
};

// the GET method...
this.doGet = function(url, hand, format) {
this.url = url;
this.handleResp = hand;
this.responseFormat = format || 'text';
this.doReq();
};

} //end ajax class??

*****************************************************HTML
CODE***************************
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/1999/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ajax Test Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script type="text/javascript" src="javascripts/ajax.js"</script>
<script type="text/javascript">
var hand = function(str) {
alert('from the hand func: ' + str);
}
var mie = new Ajax();
//mie.setMimeType('text/xml');
mie.doGet('fakeserver.php', hand);
//mie.sayHello();
//window.alert("hi there");
</script>
</head>
<body>
</body>
</html>


Thank you for any help,

eholz1
 
D

David Mark

Hello JavaScript group,

I am trying to use/learn something about using AJAX (aka JavaScript)
for web pages, etc.
I am trying to use code out of "Ajax Web Applications" by Matthew
Eernisse.

This is just a simple affair using two html pages (ajaxtest.html and
ajaxmonitor.html).

It the case of ajaxtest.html all it does is flash a window.alert on
the screen with the word "OK".

The ajaxmonitor.html polls the server and has a little timing loop.
Both of these pages work in Firefox and Safari. Needless to say IE 6
and 7 i see no results. This is on several different computers (PCs).

I have searched around, but have had no luck it getting this code to
play on IE.

I am sure I am missing something. I have an external java script file
(ajax.js) which is supposed to create an XMLHttpRequestObject class,
with some methods, properties, etc. The html page merely instantiates
the "object" and accesses methods, etc.

I will attach my ajax.js file and the ajaxtest.html code. Would you
please be so kind as to point me in the right direction so this will
work in IE as well????

Code:
*****************************************************************************
ajax.js

function Ajax() {
this.req = null;
this.url = null;
this.method = 'GET';
this.async = true;
this.status = null;
this.statusText = '';
this.postData = null;
this.readyState = null;
this.responseText = null;
this.responseXML = null;
this.handleResp = null;
this.responseFormat = 'text'; //'text', 'xml', or 'object'
this.mimeType = null;

//test function for script...
this.sayHello = function() {
this.message = 'Hello Tester!';
window.alert(this.message);
};

//init method
this.init = function() {
if (!this.req) {
try {
//try to create object for Firefox, Safari, IE7, etc.
this.req = new XMLHttpRequest();
}
catch (e) {
try {
//try to create object for later verisons of IE.
//this.req = new ActiveXObject('MSXML2.XMLHTTP');
this.req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (e) {
try {
//try to create object for later verisons of IE.
this.req = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {
//could not create an HTTPRequest Object
window.alert("cannot create object");
return false;
}
}
}
}
return this.req;
};

/* good this.init = function() {
var i = 0;
var reqTry = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP') },
function() { return new ActiveXObject('Microsoft.XMLHTTP' )} ];

while (!this.req && (i < reqTry.length)) {
try {
this.req = reqTry[i++]();
}
catch(e) {}
}
return true;
};*/

// send a request method
this.doReq = function() {
if (!this.init()) {
alert('Could not create XMLHttpRequest object.');
return;
}
this.req.open(this.method, this.url, this.async);

if (this.mimeType) {
try {
req.overrideMimeType(this.mimeType);
}
catch (e) {
// could not override mime type -- IE 6 or Opera
}

That's a silly substitute for feature detection.
}
var self = this; //fixes the loss-of-scope in inner function

I keep seeing context referred to as scope (in libraries, on blogs, in
books, etc.) Is the whole world mistaken or am I? What does the
"this" identifier have to do with the scope chain?
this.req.onreadystatechange = function() {
var resp = null;
if (self.req.readyState == 4) {
//Do Stuff Here
switch (self.responseFormat) {
case 'text':
resp = self.req.responseText;
break;
case 'xml':
resp = self.responseXML;
break;
case 'object':
resp = req;
break;
}
if (self.req.status >= 200 && self.req.status <= 299) {
self.handleResp(resp);
}
else {
self.handleErr(resp);
}

Are you running the sample from your local file system? This code is
not fit for that.
}
};
this.req.send(this.postData);
};

// set mime type method
this.setMimeType = function(mimeType) {
this.mimeType = mimeType;

};

// error handler
this.handleErr = function() {
var errorWin;
try {
errorWin = window.open('', 'errorWin');
errorWin.document.body.innerHTML = this.responseText;
}
catch (e) {
alert('An error occurred, but the error message cannot be '
+ 'displayed. This is probably because of your browser\'s '
+ 'pop-up blocker.\n'
+ '\n'
+ 'Status Code: ' + this.req.status + '\n'
+ 'Status Description: ' + this.req.statusText);
}

Another try/catch crutch.
};

// set error handle methods
this.setHandlerErr = function(funcRef) {
this.handleErr = funcRef;

};

this.setHandlerBoth = function(funcRef) {
this.handleResp = funcRef;
this.handleErr = funcRef;

};

These two methods are ridiculous (particularly the first one.)
this.abort = function() {
if (this.req) {
this.req.onreadystatechange = function() { };

I've seen this a couple of times today. What is wrong with null?
this.req.abort();
this.req = null;
}

};

// the GET method...
this.doGet = function(url, hand, format) {
this.url = url;
this.handleResp = hand;
this.responseFormat = format || 'text';
this.doReq();

};
} //end ajax class??

The author is unsure about where the class ends?
*****************************************************HTML
CODE***************************
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/1999/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ajax Test Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script type="text/javascript" src="javascripts/ajax.js"</script>
<script type="text/javascript">
var hand = function(str) {
alert('from the hand func: ' + str);
}
var mie = new Ajax();
//mie.setMimeType('text/xml');
mie.doGet('fakeserver.php', hand);
//mie.sayHello();
//window.alert("hi there");
</script>
</head>
<body>
</body>
</html>

Thank you for any help,

eholz1

So what happens when you run it in IE?
 
R

Richard Cornford

David said:
On Dec 6, 9:44 pm, eholz1 wrote:

I keep seeing context referred to as scope (in libraries, on
blogs, in books, etc.) Is the whole world mistaken or am I?

It is a pity that so many fall for this misuse of terminology as it can
only act to get in the way of a good understanding of the role of scope
in lexically scoped javascript.
What does the "this" identifier have to do with the scope
chain?

Absolutely nothing.

I've seen this a couple of times today. What is wrong
with null?
<snip>

There are XML HTTP request objects that will not allow a non-function
value to be assigned to - onreadystatechange - and so where attempting
to assign null will throw an exception (as I recall the issue was with
one of Microsoft's ActiveX versions). You can get round that by
assigning a harmless function instead, though it would be better for
that to be a reference to a single global function rather than a new
inner function each time.

Richard.
 
D

David Mark

It is a pity that so many fall for this misuse of terminology as it can
only act to get in the way of a good understanding of the role of scope
in lexically scoped javascript.

You can include the YUI developers in that group. Check out their
events module documentation sometime.
Absolutely nothing.

I didn't think I was mistaken, but I had to ask, if only to point out
that virtually the entire JavaScript community has severe
misconceptions about this very basic and critical concept. No wonder
virtually every site I visit throws script errors. I'm not talking
about the weekend warrior JS developers who don't know what a scope
chain is, but the people who are actually *teaching* JS. It reminds
me of VB, where everybody who used it was a self-proclaimed expert,
yet seemingly nobody could design a competent GUI or handle run-time
errors. I would expect such buffoonery in a community using a
derivation of BASIC, but JavaScript isn't nearly as accessible.
Perhaps it is because there is no barrier to entry (no IDE or controls
to buy.) Somebody really should put up a barrier.
<snip>

There are XML HTTP request objects that will not allow a non-function
value to be assigned to - onreadystatechange - and so where attempting
to assign null will throw an exception (as I recall the issue was with
one of Microsoft's ActiveX versions). You can get round that by

Thanks for the tip. I haven't seen that one before. I thought for
sure I tested my XHR wrapper with the three distinct ActiveX versions,
but maybe not. I know the IE7 version doesn't have this problem.
assigning a harmless function instead, though it would be better for
that to be a reference to a single global function rather than a new
inner function each time.

Yes. Well, clearly the snippet was from another bad JavaScript book.
Why would publishers pay people who don't know JavaScript to write
books on JavaScript? It would seem that having a JavaScript-oriented
blog is the only prerequisite these days. Never mind if 99% of the
posted information is nonsense.
 
R

Richard Cornford

David said:
You can include the YUI developers in that group.
Check out their events module documentation sometime.

I have seen it.
I didn't think I was mistaken, but I had to ask, if
only to point out that virtually the entire JavaScript
community has severe misconceptions about this very
basic and critical concept.

It could be a source of amusement, if it wasn't for that fact that some
of them are taken quite seriously.
No wonder virtually every site I visit throws script errors.

Last week one of our consultants was moved onto handling our web
applications, so he was introduced to a mass of web application
documentation including the one I wrote about how QA staff should
configure their browsers to be able to see javascript errors as they
happen (and properly report those errors). So he set his (IE) browser to
pop up the error dialog whenever a javascript error occurred. The next
day he came to me and expressed his concern that setting his browser up
in that way had somehow 'broken the Internet' for him, as virtually
whatever sight he visited now popped up the JScript error dialog. And I
had to explain that the general standard of Internet scripting (and QA)
is atrocious, that all of those errors had been happening all along, and
that the only difference was that they were now self-evident instead of
just being represented as a small yellow triangle going unobserved in
the bottom left of his browser window.
I'm not talking about the weekend warrior JS developers
who don't know what a scope chain is, but the people who
are actually *teaching* JS.

Or not, as the case may be.
It reminds me of VB, where everybody who used it was a
self-proclaimed expert, yet seemingly nobody could
design a competent GUI or handle run-time errors.
I would expect such buffoonery in a community using a
derivation of BASIC, but JavaScript isn't nearly as
accessible.
Perhaps it is because there is no barrier to entry
(no IDE or controls to buy.) Somebody really should
put up a barrier.

Not being "nearly as accessible" and there being no "barrier" seems a
little contradictory.
Thanks for the tip. I haven't seen that one before. I
thought for sure I tested my XHR wrapper with the three
distinct ActiveX versions, but maybe not. I know the
IE7 version doesn't have this problem.


Yes. Well, clearly the snippet was from another bad
JavaScript book. Why would publishers pay people who
don't know JavaScript to write books on JavaScript?

How would a publisher set about identifying someone as knowing, or not
knowing, javascript? Publishers having their expertise in the field of
book publishing rather than browser scripting. But the question doesn't
really arise for publishers anyway as the people who by their books
would tend to be the people who know less then the individuals who write
them, and so the publishers get their money before the reader is
anywhere near being in a position to judge what they are reading.

On the other hand, the people who write books are more likely to be
journalists than programmers (I bet you can earn a lot more as a decent
programmer than you would get for writing a book about programming). So
far in my life I have randomly got to know (sort of) two journalists.
And what I got to know about them was that they were both shockingly
(and that is shocking despite my having a strong tendency to be
extremely cynical to start with) sefl-serving, selfish, duplicitous
individuals who would sell their own grandmothers if they perceived that
as advantageous to themselves in any way. I don't see such individuals
as having any qualms about filling a manuscript with hath truths and
bullshit and then selling to the first publisher that let them.
It would seem that having a JavaScript-oriented
blog is the only prerequisite these days. Never
mind if 99% of the posted information is nonsense.

Blogs are a great way of avoiding independent peer review (by filtering
out any critical feed-back), which is where Usenet scores (as here there
is no way of stopping anybody from saying anything they want to).

Richard.
 
R

Richard Cornford

eholz1 wrote:
... . Needless to say IE 6
and 7 i see no results. ...

Whether that was "needless to say" is a matter of debate. However what
you should have said is precisely what does happen on IE 6 and 7 (what
you see, which error messages, of any, show in the error dialog) and how
that related to what you are expecting to happen.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/1999/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ajax Test Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script type="text/javascript" src="javascripts/ajax.js"</script>
<snip> ^^^

IE may be extremely tolerant of error filled tag-soup HTML but there
are some things it cannot cope with, and I bet that missing chevron at
the end of the opening SCRIPT tag is going to seriously confuse it.

Validating your mark-up can help identify such issues, but if you
validate your mark-up it is a good idea to validate it as the type of
mark-up you are using, and this mark-up is not XHTML despite any
appearance to the contrary. If it was XHTML then the whole thing never
would work with IE 6 and 7 anyway as currently Microsoft browsers do not
support XHTML.

Richard.
 
E

eholz1

I have seen it.



It could be a source of amusement, if it wasn't for that fact that some
of them are taken quite seriously.


Last week one of our consultants was moved onto handling our web
applications, so he was introduced to a mass of web application
documentation including the one I wrote about how QA staff should
configure their browsers to be able to see javascript errors as they
happen (and properly report those errors). So he set his (IE) browser to
pop up the error dialog whenever a javascript error occurred. The next
day he came to me and expressed his concern that setting his browser up
in that way had somehow 'broken the Internet' for him, as virtually
whatever sight he visited now popped up the JScript error dialog. And I
had to explain that the general standard of Internet scripting (and QA)
is atrocious, that all of those errors had been happening all along, and
that the only difference was that they were now self-evident instead of
just being represented as a small yellow triangle going unobserved in
the bottom left of his browser window.


Or not, as the case may be.


Not being "nearly as accessible" and there being no "barrier" seems a
little contradictory.






How would a publisher set about identifying someone as knowing, or not
knowing, javascript? Publishers having their expertise in the field of
book publishing rather than browser scripting. But the question doesn't
really arise for publishers anyway as the people who by their books
would tend to be the people who know less then the individuals who write
them, and so the publishers get their money before the reader is
anywhere near being in a position to judge what they are reading.

On the other hand, the people who write books are more likely to be
journalists than programmers (I bet you can earn a lot more as a decent
programmer than you would get for writing a book about programming). So
far in my life I have randomly got to know (sort of) two journalists.
And what I got to know about them was that they were both shockingly
(and that is shocking despite my having a strong tendency to be
extremely cynical to start with) sefl-serving, selfish, duplicitous
individuals who would sell their own grandmothers if they perceived that
as advantageous to themselves in any way. I don't see such individuals
as having any qualms about filling a manuscript with hath truths and
bullshit and then selling to the first publisher that let them.


Blogs are a great way of avoiding independent peer review (by filtering
out any critical feed-back), which is where Usenet scores (as here there
is no way of stopping anybody from saying anything they want to).

Richard.

Wow Again - thanks for the guidance on the ajax.js (I am happy that it
was not my code).
I am not that good enough programmer to write code quite like that.
But you should know it was from sample files from a book on AJAX from
the SitePoint publishers.

As far as my IE 6 and 7 errors - there were no errors displayed - just
no reaction or display of the little window.alert("I am working") type
message. Firefox displayed the message!
Sadly I did discover the problem short after I made this post. A
typo!!! (sorry to waste your time here). The problem was a missing ">"
at the end of this line at the ".js"
should have been: <script blah "blah.js"></script>!!

<script type="text/javascript" src="javascripts/ajax.js"</script>

Thanks for the info above, it was helpful.

eholz1
 
P

Peter Michaux

You can include the YUI developers in that group. Check out their
events module documentation sometime.

I have no problem with the word "scope" and I never did confuse that
with lexical scope. So many words in English are overloaded it just
doesn't bother me.

What would you call it? I will need a word for this soon. It could be
called "thisObj".

I didn't think I was mistaken, but I had to ask, if only to point out
that virtually the entire JavaScript community has severe
misconceptions about this very basic and critical concept. No wonder
virtually every site I visit throws script errors. I'm not talking
about the weekend warrior JS developers who don't know what a scope
chain is, but the people who are actually *teaching* JS. It reminds
me of VB, where everybody who used it was a self-proclaimed expert,
yet seemingly nobody could design a competent GUI or handle run-time
errors. I would expect such buffoonery in a community using a
derivation of BASIC, but JavaScript isn't nearly as accessible.
Perhaps it is because there is no barrier to entry (no IDE or controls
to buy.) Somebody really should put up a barrier.

I believe that the idea from the beginning was to keep the barrier
low. In ES4 the barrier to Java programmers is being lower.

[snip]

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top