Javascript Function Question

M

Mike

Hello,
I have a function called stateChanged:
function stateChanged()
{
alert(xmlHttp.readyState)
if (xmlHttp.readyState==4)....................
...............................
}



When I call it with:
xmlHttp.onreadystatechange=stateChanged()
I get an error: Type mismatch.
When I call it with
xmlHttp.onreadystatechange=stateChanged
It runs fine.
Whats wrong with the parenthesis in the function call?
Thanks
Mike
 
T

Thomas 'PointedEars' Lahn

Mike said:
I have a function called stateChanged:
function stateChanged()
{
alert(xmlHttp.readyState)

Should be

window.alert(xmlHttp.readyState);

and presumably the whole thing should not be a Function statement but a
Function expression that creates a closure (else you need globals which are
very bad style, or a wrapper object that I don't see here).
if (xmlHttp.readyState==4)....................

Don't forget to test the `status' property as well. A response may be fully
received but indicate an error.
..............................

Your dot key is malfunctioning.
}

When I call it with:
xmlHttp.onreadystatechange=stateChanged()
I get an error: Type mismatch.
When I call it with
xmlHttp.onreadystatechange=stateChanged
It runs fine.

Because that is _not_ a call, it is only an assignment expression, as expected.
Whats wrong with the parenthesis in the function call?

This is about a *callback*. The call itself must be made by the
XHR implementation (which "knows" about the status change of the
request-response-chain), not by you. Calling the function yourself
results in the property being assigned the *return value* of the
function, which so far is `undefined'.

I suppose a value of the object type is expected there, `null' or
a Function object reference, instead.

See also http://developer.mozilla.org/en/docs/AJAX


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top