Ajax is used to create asynchronous web applications. It is deployed on the client-side and makes use of several web technologies.
Ajax has made it easier to asynchronously send and retrieve data from a server without interfering with the existing page’s display and functionality.
Ajax is not a programming language, and requires a built-in browser with the XMLHttpRequest object, which requests data from the server. It also uses JavaScript and HTML DOM to display the data.
Callback functions are used to handle responses from the server in Ajax. There are two types of callback functions:
Set the value of an event handler equal to the anonymous function, as follows:
function start() {
// newxmlhttp request
var xmlhttp = new XMLHttpRequest();
// creating a post
xmlhttp.open("POST", "Demo", true);
xmlhttp.onreadystatechange=function() {
// define your callback as an anonymous function
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log("This is the callback as anonymous);
}
}
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send();
}
The anonymous function will have access to the variable set in its containing function. Whenever callback is called, the terminal will print:
This is the callback as anonymous
The XMLHttpRequest
object should be created as a global object outside the functions in the following way:
var xmlhttp = new XMLHttpRequest();
// write named callback function
function Func_CallBack() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log("This is the callback as named");
}
}
// Now just set onreadystatechange property to the name of the function.
function start() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "Demo", true);
// call our defined callback function when state changes. xmlhttp.onreadystatechange=Func_CallBack;
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send();
}
Whenever state changes, callback is called and the terminal will print:
This is the callback as named
Global variables can cause some problems; therefore, the first approach is commonly used.
Free Resources