How to Use the Callback Function in Ajax
See Ajax: Tips and Tricks for similar articles.
Callback functions are used to handle responses from the server in Ajax. A callback function can be either a named function or an anonymous function. Follow the steps below to create and use the different kinds of callback functions.
To write a callback function as an anonymous function:
- Set the value of an event handler equal to the anonymous function.
The anonymous function will have access to the variable set in its containing function.function start() { var xmlhttp = new XMLHttpRequest(); var contentDiv = document.getElementById("Content"); xmlhttp.open("POST", "Demo", true); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { console.log(xmlhttp.responseText); } } xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.send("FirstName=Nat&LastName=Dunn"); }
To write a callback function as a named function:
- Create an
XMLHttpRequestobject in the global scope (outside of the following two functions).var xmlhttp = new XMLHttpRequest(); - Write a function to use as the callback function.
function myCallBack() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { console.log(xmlhttp.responseText); } } - Set the value of the onreadystatechange property to the name of the function.
The problem with this approach is that it uses global variables, which can be problematic.function start() { var xmlhttp = new XMLHttpRequest(); var contentDiv = document.getElementById("Content"); xmlhttp.open("POST", "Demo", true); xmlhttp.onreadystatechange=myCallBack; xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.send("FirstName=Nat&LastName=Dunn"); }
To write a callback function as a named function without using global variables:
- Write a function to use as the callback function, which accepts the
XMLHttpRequestobject as a parameter.function myCallBack(xmlhttp) { if (xmlhttp.readyState==4 && xmlhttp.status==200) { console.log(xmlhttp.responseText); } } - Set the value of the
onreadystatechangeproperty to an anonymous function. Inside the anonymous function, call the callback function and pass theXMLHttpRequestobject as an argument.function start() { var xmlhttp = new XMLHttpRequest(); var contentDiv = document.getElementById("Content"); xmlhttp.open("POST", "Demo", true); xmlhttp.onreadystatechange=function() { myCallBack(xmlhttp); }; xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.send("FirstName=Nat&LastName=Dunn"); }
