Forum Moderators: open

Message Too Old, No Replies

a question on AJAX

concerning onreadystatechange

         

mehh

2:55 pm on Feb 18, 2007 (gmt 0)

10+ Year Member



i was looking through DynamicDrive's AJAX section and found a script that caught my eye. i had a look at the code for it and found something odd. it had no onreadystatechange function. instead it had this:

page_request.open('GET', url, false)
page_request.send(null)
someFunction(page_request)

so my questions are as follows.
Is onreadystatechange actually needed?
What are the advantages of it? and
Why do most AJAX scripts use it at all if it is not necessary?

scriptmasterdel

4:29 pm on Feb 18, 2007 (gmt 0)

10+ Year Member



onReadyStateChange

As the name kind of implies, every time the "ready state" changes this function will be executed.

When the property readyState is 4 that means the response is complete and we can get our data.

Then the function that is repeatedly called can use the information depending on the readyState.

This basically ensures that only if the request has completed correctly your script will execute as you wish.

Del

mehh

5:28 pm on Feb 19, 2007 (gmt 0)

10+ Year Member



thanks for the response but it wasn't really what i was looking for. let me rephrase the question:
why use onreadystatechange if there is an alternative which doesn't require checking the page request to see if it has finished?

penders

11:40 pm on Feb 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Most AJAX scripts will run asynchronously - so you can send off the request to the server in the background and carry on doing things at the client end, waiting for a response from the server - this is when you need the onreadystatechange.

However, 'AJAX' scripts can also run 'synchronously' (which is kinda AJAX without the 'A'?!) - in which case the script waits for a response from the server, no background processing, your script is stuck until you get a response. No need for the onreadystatechange.

page_request.open('GET', url, false)

With a 3rd parameter set to false, the script seems to be opening a synchronous request - so no need for onreadystatechange in this case (AJAX without the 'A'). This needs to be true for a regular asynchronous AJAX request.

(Well, I believe that's the idea... I'm no AJAX expert!)

mehh

2:07 pm on Feb 21, 2007 (gmt 0)

10+ Year Member



thanks.