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;
}
}
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.
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:
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
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.