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 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:
var req = new XMLHttpRequest();
We have used two methods with the Ajax object:
- open( ): This method is used to open the request call with the server
- send( ): This method is used to send the request.
req.open("GET", "API LINK", true/false);
The open( ) method takes three parameters that are explained below:
- GET: The first parameter tells the nature of the request it could be get or post.
- API LINK: The second parameter is the API link to which we want to communicate.
- true/false: The third parameter tells whether the request is asynchronous or synchronous. When it is true means it is asynchronous otherwise it is synchronous.
Example 1: This example illustrates the Ajax Call.
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! “.
Welcome to GFG!
Please Login to comment...