views:

264

answers:

1

Problem description: Hello !

My XMLHTTPRequest object, when ready, does a couple of things, as in, the responseText which i receive, is split up, and sent as a parameter to myFunction() Now, i need to call myFunction() 'n' number of times, with substrings of the response text as parameters.

This Works:

myAjaxObj.onreadystatechange=function() 
    {   
        if(myAjaxObj.readyState==4) 
        {
            if(myAjaxObj.status==200) 
                        {
                            myFunction( myAjaxObj.responseText, id )

This DOESNT Work:

myAjaxObj.onreadystatechange=function() 
    {   
        if(myAjaxObj.readyState==4) 
        {
            if(myAjaxObj.status==200) 
                        {
                            var count i=0;
                            for( i=0; i < 5; i++ )
                            {   
                                [b]alert("Without this it wont work") [/b]
                                myFunction( myAjaxObj.responseText, i );
                            }

Basically, the code within the for-loop wont run, unless the alert() is uncommented. Ive read somewhere about javascript closures, and the facts that it kinda gives the execution/rendering to get in sync

What would be the solution?

+1  A: 

OK, this is happening because you are not polling your onreadystatechange function. Basically, the call is asynchronous and you need to poll your readyState variable every few milliseconds to see when it changes. This is the reason it is working with the alert() - the alert is causing a long pause during which the AJAX response is recieved by the client. The readyState variable is checked after the alert has got a response and your code executes as needed.

However, without the alert(), your code checks for the readyState variable just once

One way around is to make the call synchronous by setting the asynchronous parameter to false in the call. This has a downside that the client will freeze until the AJAX response is received.

Another way is to keep polling the readyState variable.

Basically, you should not trust the callback function to execute itself properly - it gets stuck many times!

Crimson
I'm not sure this explain the scenario in the question. readyState 4 is the final state so I can't see how the presence of the alert affects anything.
AnthonyWJones