0

I'm learning Ajax and I'm going through this example. What does this do? I don't understand the syntax variable = function(){ how is a function being assigned to a variable?

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
Celeritas
  • 14,489
  • 36
  • 113
  • 194
  • Functions are first class objects in java script: http://stackoverflow.com/questions/705173/what-is-meant-by-first-class-object – Jakub Kaleta Aug 09 '12 at 18:19

4 Answers4

2

When readyState changes, if request finished and response is ready (readyState==4) and document loaded correctly (HTTP Status Code 200 = OK!), append response text to the element with id #txtHint.


onreadystatechange stores a function (or the name of a function) to be called automatically each time the readyState property changes.

readyState holds the status of the XMLHttpRequest. Changes from 0 to 4:

  • 0: request not initialized
  • 1: server connection established
  • 2: request received
  • 3: processing request
  • 4: request finished and response is ready

status takes HTTP response codes:

  • 200: "OK"
  • 404: Page not found
Edward Ruchevits
  • 6,411
  • 12
  • 51
  • 86
2

I know everyone is saying it's a callback specifically but the question you asked could better be answered by comparing what you're puzzled over with some more familiar code.

function myFunction()
{
    ...
}

So we know that calling myFunction() will run that code.

In Javascript, you can declare a function in a number of ways. This means that this:

var myFunction = function()
{
    ...
}

Does exactly the same as the first example above. It creates a function that you can call using myFunction().

Add the callback into the mix in your question and we can see that

xmlhttp.onreadystatechange = function()
{
    ...
}

is nothing more than assigning a function and containing code to the onreadystatechange property of object xmlhttp. Meaning that your code within the function will be called every time there is a state change in the xmlhttp object.

David Barker
  • 14,484
  • 3
  • 48
  • 77
1

onreadystatechange is a callback. It gets triggered when a particular event happens. onreadystate is happens when the requests ready state changes.

In short onreadystate

Stores a function (or the reference of a function) to be called automatically each time the readyState property changes

Now for the line xmlhttp.readyState==4 && xmlhttp.status==200

readyState : Holds the status of the XMLHttpRequest.

 Changes from 0 to 4: 
0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready

And status Holds status

200: "OK"
404: Page not found

So xmlhttp.readyState==4 && xmlhttp.status==200 condition is true when the response is ready and there is no issues

xmlhttp.responseText contains the response sent from the server.

So document.getElementById("txtHint").innerHTML=xmlhttp.responseText; changes the HTML of the element with id txtHint to the response that was received.

Hope all the above made sense!!!

Clyde Lobo
  • 9,126
  • 7
  • 34
  • 61
  • I've never been able to understand callbacks. `onreadystatechange` gets triggered when a particular event happens. What does this have to do with a call back? – Celeritas Aug 09 '12 at 18:31
  • A call to a function when a particular event occurs is called `callback`. Does it make sense now?? – Clyde Lobo Aug 09 '12 at 18:33
  • What do you mean when a particular event occurs? Just calling a function normally wouldn't be considered a callback right. – Celeritas Aug 09 '12 at 19:42
  • Thats one example. Read http://www.impressivewebs.com/callback-functions-javascript/ for a better understanding – Clyde Lobo Aug 09 '12 at 19:45
1

I'd like to address this comment: I've never been able to understand callbacks.

Consider this analogy:

You need want to rent that movie that just came out on VHS, so you call Blockbuster and ask the attendant if they have a copy. Sadly though, they are super busy dealing with thousands of David Bowie fans who are trying to rent "Labyrinth" all at the same time and he does't have time to look up the information for you. So instead, he asks for your phone number. At some point in the future when the hordes of people have left and he has the time, he looks up the info you need, and calls you back on the number you provided. Turns out the movie is sold out though, so he suggests "Dark Crystal" instead.

In your case you are dealing with an entity that is going to take a long time to do it's work as it needs to talk to remote servers, so it essentially asks you for your phone number so that when it's done you are called back as it were, with the requested data.

Does it make more sense now?

asawyer
  • 17,642
  • 8
  • 59
  • 87
  • A long time ago my friend who hates computers took a class with me. When he asked the teacher what a key (in an array) was she said "it's like a key to the post boxes in an apartment building". I'm not a huge fan of learning through analogies/metaphors. When you say "you are dealing with an entity that is going to take a long time to do it's work" what does it matter? It's got nothing better to do? There's no instructions it can do in the mean time. – Celeritas Aug 09 '12 at 19:48
  • 1
    @Celeritas Just because that's the cause in your specific example doesn't mean that's the general case. Consider this - Javascript is single threaded. If you made an ajax call that took maybe 3 seconds, (totally reasonable) you would completely lock up any other script on the page and kill all user interaction during that period. Still think there are no instructions to be run in the mean time? – asawyer Aug 09 '12 at 19:51
  • @Celeritas Also the teachers analogy was not that great, besides arrays have indexes not keys. – asawyer Aug 09 '12 at 19:55