What is polling in AJAX ?
Last Updated :
16 Nov, 2022
In this article, we will see the polling with AJAX. Here, we are trying to create a polling-like experience using Javascript features like AJAX and Fetch API.
Polling is the process of constantly and successively making HTTP calls until a required response is received. It is a very basic method to create real-time updates in the application. Polling is not very different from simple HTTP requests.
In the below diagram, the client is making a continuous request to the server until it gets its response. The server returns an empty response until it finds the answer to the request. The problem with Polling is that the client has to keep asking the server for any new data. As a result, a lot of responses are empty, creating HTTP overhead. The purpose of polling is to be in touch with the server content. It can be used in real-time applications but it can cause a high usage of network resources.
Asynchronous Javascript And XML(AJAX): It is used to make asynchronous HTTP calls using javascript. It is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance.
Fetch API: An API that is used to make an HTTP request in Javascript. The Fetch API provides the fetch() method defined on a window object. This is used to perform requests. This method returns a Promise which can be further used to retrieve the response to the request.
Types of Polling:
- Short Polling: In this case, Here the client never waits for the server response and hence gets an empty response when the server is not ready with the answer.
- Long Polling: In this kind of polling, the client waits until it gets the appropriate response from the server, and hence, here, the request/response cycle is long-lived.
Approach: The following workflow of the HTTP polling, will be utilized to perform the required task, which is described below:
- Initially, the client makes an HTTP request to the server.
- The server processes this request.
- The server either returns an empty or fulfilled response.
- The client gets the response.
- The client repeats sending the request until it gets the needed resources from the server.
Note: We are making a call to https://jsonplaceholder.typicode.com/todos/1 in the below examples.
Example 1: In this example, we will make a simple AJAX request which is the basic building block of Polling in Javascript.
Steps:
- Using XMLHttpRequest to make an HTTP request.
- Consoling the response on the console tab with onload event.
HTML
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3>Explain what is polling in AJAX.</h3>
</body>
<script>
const xhr = new XMLHttpRequest();
xhr.onload = (ev)=>{
if(ev.target.status == 200){
console.log("response received!");
}
}
xhr.open("GET","https://jsonplaceholder.typicode.com/todos/1",true);
xhr.send();
</script>
</html>
Output: Open the console tab of the browser to see the output:
Example 2: In this example, we will call the send method constantly after every second to poll the server.
Steps:
- Using XMLHttpRequest to create an instance of AJAX.
- Using open( ) to create the HTTP request.
- Using send( ) to send a GET method request.
- Using onload event to get the response.
- Using setInterval to send the request every second.
So, This polls the server by sending a request every second.
HTML
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3>Explain what is polling in AJAX.</h3>
</body>
<script>
const xhr = new XMLHttpRequest();
xhr.onload = (ev)=>{
if(ev.target.status == 200){
console.log("response received!");
}
}
setInterval(()=>{
xhr.open("GET","https://jsonplaceholder.typicode.com/todos/1",true);
xhr.send();
},1000)
</script>
</html>
Explanation: We are getting an output from the server for every second and hence a text message "response received" is getting consoled as shown in the output below. Open the console tab of the browser to see the output.
Output:
Example 3: In this example, we will perform polling using the fetch API in Javascript where we are making a request for every second.
Syntax for fetching:
fetch(" url ")
.then((res)=> {
})
.catch((err)=> {
}
Steps:
- Using Fetch( ) to send the HTTP request
- Using then( ) to get the response
- Using setInterval( ) to send the request every second
HTML
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3>Explain what is polling in AJAX.</h3>
</body>
<script>
setInterval(()=>{
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => {console.log("response received!")})
},1000)
</script>
</html>
Output: Open the console tab of the browser to see the output.
Similar Reads
What is Ajax ? Imagine browsing a website and being able to submit a form, load new content, or update information without having to refresh the entire page. That's the magic of AJAX. Asynchronous JavaScript and XML (AJAX) is a web development technique that allows web pages to communicate with a web server asynch
5 min read
What is Long Polling and Short Polling ? In this article, we will know about the Polling concept, along with knowing the different types of Polling available, with an understanding of the basic differences between them & the related code examples.Polling simply means checking for new data over a fixed interval of time by making API cal
5 min read
Polling in System Design Polling in system design is an important method for gathering data or monitoring device status at regular intervals. This article provides an overview of polling, its importance, applications, strategies, and challenges also. Important Topics for Polling in System Design What is Polling?Importance o
10 min read
Explain JSON in AJAX AJAX is a very popular concept that is used to update the page without reloading the page. AJAX stands for Asynchronous Javascript And XML and because of that many Developers think that AJAX will only use XML to export and import data but that is not true. AJAX can use XML to transport any kind of d
5 min read
What is data-ajax attribute? The data-ajax attribute is a custom HTML attribute used for storing AJAX-related information in an element, guiding JavaScript interactions, and AJAX requests for dynamic content loading or updates. The data-ajax attribute allows to activation of unobtrusive AJAX. Unobtrusive AJAX is an add-on on jQ
3 min read