Ajax Request in JavaScript

Ajax stands for asynchronous JavaScript and XML. Ajax is used to get the data from the server without refreshing the page. Classic example of Ajax is Google search bar. As you start typing the search term in search bar, Google page sends the Ajax request to server and shows you the list of suggestions giving better user experience.

Below example shows how to work with ajax request in JavaScript. Here we have defined one function “processAjax”. It will send the ajax request (using XMLHttpRequest class) to server to get xyz.json file. When the request is completed, it prints the response got from the server.

function processAjax() {
var xmlhttpRequest = new XMLHttpRequest();

xmlhttpRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log (“Response from the server is -> ” + this.responseText);

//set the XMLHttpRequest parameters
xmlhttpRequest.open(“GET”, “xyz.json”, true);

//send the request

You may also like...