Ready State

Previously I said that we need to define a method to be called once the request state changes and that this is done by setting the onreadystatechange property; you should note that I said 'state changes', not 'complete' - for those are two completely different things. The best way to show this is by way of example, incorporating everything that we have learnt so far. Put the following in one file:

<script>
    var xmlhttp = false;
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (trymicrosoft) {
      try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (othermicrosoft) {
        try {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (failed) {
          xmlhttp = false;
        }
      }
    }

    function goAJAX() {
             alert("Initial Ready State is:"+xmlhttp.readyState);

         xmlhttp.onreadystatechange = myReturnMethod;
         xmlhttp.open("GET", "another_file.html", true);
         xmlhttp.send(null);
     }

     function myReturnMethod() {
          alert("New Ready State is:"+xmlhttp.readyState);
     }
</script>
<button onclick="javascript:goAJAX()">Let's try it!</button>

In the file being requested we can fill it with anything we desire, we are not going to use it's contents yet, as long as it is able to be found.

When the button is pressed we should notice that the readystate alert appears multiple times and eventually it will show the readyState equal to 4. Different browsers handle this differently, in Safari it counts nicely from 0-4 but in firefox it has 1 appear twice and 0 only appears on the first time it is run. Thankfully for us, we are only interested when the readyState is 4, but for the sake of completeness let's see what those numbers actually mean.

  • 0: uninitialised - the object contains no data, prior to open being called
  • 1: object is loading its data - prior to send being called
  • 2: loaded - the request has been sent
  • 3: interactive - the request is being processed and some data maybe available but is incomplete and thus unsafe to use
  • 4: complete - the request is complete and the resultant data is safe to use

Armed with this new information we can change myReturnMethod to only have the alert appear when the request is complete.

     function myReturnMethod() {
         if (xmlhttp.readyState==4){
              alert("New Ready State is:"+xmlhttp.readyState);
         }
     }

Do you need help with AJAX? Gain advice from Builder AU forums

Comments

1

Anonymous code - 12/07/06

I don't think anyone really uses

xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

anymore - that's so old-school.

Get with the times dude.

» Report offensive content

2

Shawn - 06/09/06

'old school'? old and works is better than new and shaky. Just because its old doesnt mean you cant or shouldnt do it. If it works for the situation then by all means you SHOULD use it. The biggest problem in the code community is that people think they have to have new tricky ways of doing things. Even XHTML and DHTML are sometimes better choices over top of CSS and other options - depending on what you are doing.

» Report offensive content

3

Ari - 15/09/06

Agree with Shawn: clear, functional and importantly, relevant code is always preferred to the latest and greatest...

» Report offensive content

4

d - 09/12/06

5

shailender - 10/01/07

I too agree with Shawn,

.Net 2.0 gives easy ways of developing AJAX enabled websites.

Differnt AJAX Toolkits are available, Better use that to increase effective coding with less effort and time.

» Report offensive content

6

Zenlogic.com.au - 02/03/07

Good intro to the mechanics of AJAX, but there are so many frameworks and toolkits around that wrap the request object and provide error handling and the like, it would be daft to roll-your-own. However it is always good to understand the inner workings, which are quite simple ultimately.

Re "When to use AJAX" it does appear AJAX is here to stay, but its use should be an architectural decision as much as an aesthetic one. Choosing what to AJAX-ify, how to design the services layer, and which toolkits to use are crucial issues and must be considered early on. AJAX also adds a whole extra dimension to testing, security, performance etc that are easy to overlook.

7BECFD

» Report offensive content

7

Nazi - 21/06/07

How can i get data on readystate = 3? i want to get continous http data from server but unable t get incompete response.can anybody help me to do so

» Report offensive content

8

arjunsdk - 08/08/07

hey how do you take information back from servlet?

script recognizes req.status==200.

How to read the servlet?

pls reply to c.achuth@gmail.com

pls!!!!!!!!!!!!!!!!!

The below doesnt recieve and write .

function showtag()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
xmlHttp.onreadystatechange=stateChanged;
var url="http://localhost:8084/usebean/proc2"

xmlHttp.open("GET",url,true);

xmlHttp.send(null);
alert("job over");
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{

var response = xmlHttp.responseXML;
var res=xmlHttp.responseText;

var message = response.getElementsByTagName("message")[0];
alert("45");
eval(xmlHttp.responseXML);
alert("44");
document.myForm.time.value = 55;

alert("");
document.getElementById("message").innerHTML;

setMessage(message.childNodes[0].nodeValue);

}
else if (xmlHttp.readyState==3)
{
alert("3");
}
else
{

}

return;
}
_______________________________________________________
----------------------------------------------------------------------------------
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

» Report offensive content

9

kamal_barna22 - 04/11/08

ajax through coding with object XMLHttpRequest and ajax update panel
which is more helpful in asp.net 2.0

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

9

kamal_barna22 - 11/04/08

ajax through coding with object XMLHttpRequest and ajax update panel which is more helpful in asp.net 2.0 ... more

8

arjunsdk - 08/08/07

hey how do you take information back from servlet? script recognizes req.status==200. How to read the servlet? pls reply to c.achuth@gmail.com pls!!!!!!!!!!!!!!!!! The below doesnt recieve ... more

7

Nazi - 21/06/07

How can i get data on readystate = 3? i want to get continous http data from server but unable t ... more

Log in


Sign up | Forgot your password?

  • Staff Microsoft shows off IE9 preview

    This week, highlights from Microsoft's MIX10 conference and more in the Roundup. Read more »

    -- posted by Staff

  • Chris Duckett IE9's H.264 vote killed Ogg

    In a split decision by the judges, the winner of the W3C/WHATWG video codec consensus is H.264, taking home the future of video playback on the internet while loser Ogg goes home with nothing but thoughts of what might have been. Read more »

    -- posted by Chris Duckett

  • Staff Google launches Apps Marketplace

    Google launches and app store, while Mozilla plans to re-write its open-source license. More of this week's news in the Roundup. Read more »

    -- posted by Staff

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!