Open In App

How to create own Ajax functionality ?

In this article, we will discuss how to create my own ajax functionality. But before moving to create a functionality we will discuss ajax.

Ajax: Ajax stands for Asynchronous JavaScript and XML. It is used to communicate with the server without reloading the web page so it helps in a better user experience. So if we want to make any changes to any part of the web page without reloading the whole web page then we can use the Ajax call.



Ajax working: As we know requests could be either synchronous or asynchronous. In the case of the synchronous request, we wait till the time request has been completed in order to execute the next request.

But in the case of the asynchronous request, we didn’t wait for the request to be resolved in order to execute the next task. We execute the next task. Ajax works asynchronously. In the background, it updates our web page by communicating with the server without reloading the whole web page.



We can create an Ajax object with the help of the below syntax:

Syntax:

var req = new XMLHttpRequest();

We have used two methods with the Ajax object:

req.open("GET", "API LINK", true/false);

The open( ) method takes three parameters that are explained below:

Example 1:  This example illustrates the Ajax Call.




function printUser()
{
    var xhr = new XMLHttpRequest();
    xhr.onload = function()
    {
        var response = JSON.parse(xhr.response);
        for(let i=0;i<5;i++)
        {
            console.log(response[i]['login']);
        }
    }
    xhr.open('get','https://api.github.com/users',true);
    xhr.send();
}
printUser();

Output:

mojombo
defunkt
pjhyett
wycats
ezmobius

In this case, we are requesting the GitHub API to give the list of users and we are printing the first 5 users.

Create own Ajax functionality: In this case, create a function printMessage and passed a callback function to it. And that callback function will simply print the value of response that it will get. Inside printMessage function, we have created an Ajax object and then requested our sample.txt file. Inside our sample.txt we have the message “Welcome to GFG!”

As we are passing that response object to the callback function and inside call-back function we are just printing it.

Example 2: In this example, we have created a sample.txt file and inside it, we have written, “Welcome to GFG! “.




function printMessage(callback)
{
    var xhr = new XMLHttpRequest();
    xhr.open('get','sample.txt',true);
    xhr.onload = function()
    {
        callback(xhr);
    }
    xhr.send();
}
printMessage(function(request){
    console.log(request.responseText);
});

Output:

Welcome to GFG!

Article Tags :