472,989 Members | 3,039 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,989 software developers and data experts.

Handle OnReadyStateChange with array of XMLHTTP objects

I'm trying to make use of XMLHTTP object, but I've come across a
problem.
It seems that there is no way to create dynamic array of such XMLHTTP
objects (to make several requests) and handle them properly.
I was trying to use such code:

<script lang="javascript">

function handleOnReadyStateChange() {
if (this.readyState==4) {
//some actions
}
}

function createObjArray() {
var XmlHttp = new Array();

for (var i = 1; i<=10; i++) {
XmlHttp[i] = new ActiveXObject("Msxml2.XMLHTTP");
XmlHttp[i].open("GET", url, true);
XmlHttp[i].onreadystatechange = handleOnReadyStateChange;
}
}

createObjArray();
</script>

Unfortunately when event handler function is accessed, 'this' isn't
set to an object which fired event.

I was doing literally EVERYTHING (or at least I think so) to make it
work but ... with no success.

Behavior of this handler is somehow different from what I was used to,
because I could with no problem do similiar task with Image object.

<script lang="javascript">

function handleImgOnLoad() {
document.getElementById(this.name).src = this.src;
document.getElementById(this.name).width = Math.round(this.width/4);
document.getElementById(this.name).height =
Math.round(this.height/4);
}

function createImageArray {
var images = new Array();

for(i=1;i<=10;i++) {
images[i] = new Image();
images[i].src = 'some_url';
images[i].name = i;
images[i].onload = handleImgOnLoad;
}
}

createImageArray();
</script>

So my guess is that problem lies in XMLHTTP object which doesn't set
reference to itself in its event handler.

Does anyone knows if it is possible to do what I'm trying to do ?
I would really appreciate any help.
Jul 20 '05 #1
6 3220
k_******@hotmail.com (Krzysztof Kubiak) writes:
I'm trying to make use of XMLHTTP object, but I've come across a
problem.
It seems that there is no way to create dynamic array of such XMLHTTP
objects (to make several requests) and handle them properly.
I was trying to use such code:

<script lang="javascript">

function handleOnReadyStateChange() {
Here "this" does refer to an instance of ActiveXObject, as can be seen
by adding:
alert([this,this instanceof ActiveXObject,this.readyState]);
So the "this" is set, it's just the readyState that is broken?
Or it is not the actual object, but another instance?
for (var i = 1; i<=10; i++) {
XmlHttp[i] = new ActiveXObject("Msxml2.XMLHTTP");
I noticed that this doesn't create a new object each time, but the
same object several times. You can see this if you add:
if (i>1) {alert([i-1,i,XmlHttp[i]==XmlHttp[i-1]]);}

Behavior of this handler is somehow different from what I was used to,
because I could with no problem do similiar task with Image object.
Well, it's a host object. They can do pretty much anything they want,
and still be in compliance with the ECMAScript standard.
<script lang="javascript">
type="text/javascript"
!
for(i=1;i<=10;i++) {
images[i] = new Image();
images[i].src = 'some_url';
images[i].name = i;
images[i].onload = handleImgOnLoad;
I suggest adding the onload hander before setting the src property.
That way an already cached image can't be considered loaded *before*
the handler is set.
So my guess is that problem lies in XMLHTTP object which doesn't set
reference to itself in its event handler.
It sets something that is an instance of ActiveXObject. And the same
object every time (at least according to ==).
Does anyone knows if it is possible to do what I'm trying to do ?
I would really appreciate any help.


Can't help you, sorry. Just noticing some more odd behavior.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
Lasse Reichstein Nielsen <lr*@hotpop.com> writes:
Here "this" does refer to an instance of ActiveXObject, as can be seen
by adding:
alert([this,this instanceof ActiveXObject,this.readyState]);
Another wonder was that I added:

var n;
for(var i=1;i<XmlHttp.length;i++) { // I made XmlHttp global for this
if (this == XmlHttp[i]) {n=i;break;}
}
alert([this,n]);

The wonder is that they all compare equal to XmlHttp[1]. However, if
I change == to ===, this is not equal to any of the XmlHttp elements.
I noticed that this doesn't create a new object each time, but the
same object several times. You can see this if you add:
if (i>1) {alert([i-1,i,XmlHttp[i]==XmlHttp[i-1]]);}


But now I can't reproduce that. Probably me seeing spooks.
Anyway, a solution is to not use the same handleOnReadyStateChange
function for all the requests, but create a new one for each request
that knows what object it belongs to:

function makeHandleOnReadyStateChange(XmlHttp) {
return function() {
if (XmlHttp.readyState == 4) {
alert(self.responsText); // or something
}
}
}

and then in the loop:

XmlHttp[i].onreadystatechange = makeHandleOnReadyStateChange(XmlHttp[i]);

It seems to work.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #3


Lasse Reichstein Nielsen wrote:
k_******@hotmail.com (Krzysztof Kubiak) writes:

I'm trying to make use of XMLHTTP object, but I've come across a
problem.
It seems that there is no way to create dynamic array of such XMLHTTP
objects (to make several requests) and handle them properly.
I was trying to use such code:

<script lang="javascript">

function handleOnReadyStateChange() {

Here "this" does refer to an instance of ActiveXObject, as can be seen
by adding:
alert([this,this instanceof ActiveXObject,this.readyState]);
So the "this" is set, it's just the readyState that is broken?
Or it is not the actual object, but another instance?


It is the window object, try
window === this
inside the event handler. And yes
window instanceof ActiveXObject
is true, any host object in IE/Win will probably yield true of
instanceof ActiveXObject.

The problem is with the onreadystatechange event handler not being set
up to have this point to the object the handler is attached to (and
firing on).
With IE this remains the window (global) object but with
Mozilla/Netscape it is not better as there this in the
onreadystatechange handler is the function itself.
And the usual way with evt.target respectively window.event.srcElement
doesn't work either, Mozilla doesn't even set the evt parameter and IE
doesn't set the srcElement.
So indeed the only way for the onreadystatechange handler to reliably
access the object it is firing on is using a closure.

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #4
Lasse Reichstein Nielsen <lr*@hotpop.com> wrote in message news:<sm**********@hotpop.com>...
Lasse Reichstein Nielsen <lr*@hotpop.com> writes:

<... snip>

Anyway, a solution is to not use the same handleOnReadyStateChange
function for all the requests, but create a new one for each request
that knows what object it belongs to:

function makeHandleOnReadyStateChange(XmlHttp) {
return function() {
if (XmlHttp.readyState == 4) {
alert(self.responsText); // or something
}
}
}

and then in the loop:

XmlHttp[i].onreadystatechange = makeHandleOnReadyStateChange(XmlHttp[i]);

It seems to work.
/L


Thanks for pointing me in the right direction. Now I can handle each
object in the proper manner, although I still have a problem which I
will probably not solve until next year ;)

Each of the created event handlers responses independently, but it
seems that I'm not getting proper responses.
The reason why I'm using this loop to create XmlHttp objects is to
find if sequential images exists. I'm iterating through the subsequent
images (http://myserver.net/img001.jpg,
http://myserver.net/img002.jpg, etc.) and if I get XmlHttp.statusText
== 'OK' and XmlHttp.getResponseHeader("Content-Type") == 'image/jpeg'
I'm incrementing counter on the page (inside each of the handlers)
like this:
document.getElementById('counter').innerHTML =
parseInt(document.getElementById('counter').innerH TML) + 1;

Now I only get proper Content-type inside first handler, the other
ones give me Content-Type = 'text/html'.
I was wondering what 'arrives' in these responses and it was some
non-default 404 page, which means that file was not found on the
server (I know it is definitely there).
So ... I guess I know what I'll be dealing with, after New Year's Eve
party.

Once again thanks for your answers
Jul 20 '05 #5


Krzysztof Kubiak wrote:

The reason why I'm using this loop to create XmlHttp objects is to
find if sequential images exists. I'm iterating through the subsequent
images (http://myserver.net/img001.jpg,
http://myserver.net/img002.jpg, etc.)


If you only want to check whether a resource exists on the server then I
strongly suggest not to send a HTTP GET request but only a HTTP HEAD
request e.g. use
XmlHttp[i].open("HEAD", url, true);
That way the server sends only the HTTP response headers back but not
the complete image.
--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #6
On Wed, 31 Dec 2003 14:53:33 +0100, Martin Honnen <ma*******@yahoo.de>
wrote:
If you only want to check whether a resource exists on the server then I
strongly suggest not to send a HTTP GET request but only a HTTP HEAD
request e.g. use
XmlHttp[i].open("HEAD", url, true);
That way the server sends only the HTTP response headers back but not
the complete image.


Watch out on many java servers, they often jsut wack out a 500 if you
try a head on them. (not relevant for static images of course, but if
you're checking other pages.)

Jim.
--
comp.lang.javascript FAQ - http://jibbering.com/faq/

Jul 20 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Jacob Friis Larsen | last post by:
Anyone know how to let processReqChange know that it is in an object? In Php I can do it like this: array($this, 'function_name'); Any idea for a workaround? /Jacob function ajax () { ...
39
by: tydbowl | last post by:
I have a problem where the below code chunk causes handle leaks on some machines. The leak APPEARS to be handles to the registry key: HKCU\Software\Microsoft\Windows\CurrentVersion\Internet...
2
by: Dustin | last post by:
I found a solution to my problem in the topic called "OOP (and the XMLHttpRequest)". You may find it useful to reference to see what I have done so far. I am making a small AJAX helper object...
2
by: jhullu | last post by:
hello, I'm writing a program using XMLHttpRequest that works in the main case on IE and mozilla but this code works only on IE ... why ? probleme is located at mark 'HERE' at the end of code....
2
by: petermichaux | last post by:
Hi, I thought it is about time I tried writing some JavaScript with XMLHttpRequest instead of just using the Yahoo! UI library. The simple page below works in both Safari and Opera but I don't...
10
by: HugeBob | last post by:
Hi All, I'm having a problem with a web app I'm writing. I have a form for which I'm going to validate one of the fields. I use AJAX to retrieve XML containing a list of valid entries. My app...
5
by: Heofz | last post by:
Hey all, I've been banging my head against a brick wall on this one for the last 12 hours, and the time has come for me to give up and consult the gurus on this one. The below URL contains a...
1
by: bgold12 | last post by:
I have a page that calls a javascript function every second using setInterval(): ... <body onload="setInterval('UpdateMessages(1);', 1000 );"> ... In UpdateMessages(), I create an AJAX...
1
by: Mike | last post by:
Hello, I have this: function process(a,b) { xmlHttp=GetXmlHttpObject(); //alert(xmlHttp) if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
3
SueHopson
by: SueHopson | last post by:
Hi All, I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.