View Full Version : Why we use this sequence????
12-04-2008, 03:28 PM
Every time, welll almost, when we create a XMLHttpRequest we write the following, for example:
1.XMLHttpRequest .onreadystatechange = showPictures;
2.XMLHttpRequest .open("GET", "file.xml", true);
The question is why??? I find it more logical if the XMLHttpRequest .onreadystatechange was last. Thank you
12-04-2008, 03:44 PM
Actually, it makes more sense to set up all your object's parameters before calling a function that procedes to utilize those parameters. For example, if your open() is not asynchronous, then it won't assign your onreadystatechange() to your xmlhttp object until after the send is complete.
12-04-2008, 05:06 PM
Yes you are right indeed. But now I have another question. When does the response arrive?? It doesn't necessarily readyState = 4. After the open() calling or after the send() calling??? And I believe this doesn't matter if the call is sychronous or asychronous. Thank you again
12-04-2008, 06:07 PM
Regardless as to whether your xmlhttprequest is async or not, as soon as your entire response is received, your readyState will switch to 4. Every time the readyState is changed, your onreadystatechange handler will run.
12-04-2008, 07:29 PM
Yes yes, I agree with you. One more question and I believe I am OK with this. If I write "onreadystatechange " after "send()", is there a possibility the response to be completed before the "onreadystatechange" function is called????
12-04-2008, 07:45 PM
First, you're actually defining onreadystatechange, not calling it (the xmlhttp object is doing that natively).
If you define your onreadystatechange after your send():
- If you're request is not async, you won't have an onreadystatechange at all because it won't define it until the requested data has been received.
- If you're request is async, then yes, you are running the risk of not defining your onreadystatechange in time to catch your readyState==4. I tested a few browsers and all of them missed the state change to 1, some missed all 4 (the move from 3 to 4 would depend on your target data's filesize).
Just from a logical point of view, it's a horrible idea to set the onreadystatechange after your send() - it just doesn't make sense. I can't really think of a case where you'd want to do this.
12-04-2008, 08:21 PM
I wrote the "onreadystatechange" after send() using a async request and I lost readystate=1, but when I wrote it on top I "catched" it.
I found out my mistake, I found out why I was thinking wrong. Thank you for help!!!!!!!
12-04-2008, 09:21 PM
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.