Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptWhat is polling in AJAX ?

What is polling in AJAX ?

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">
        neveropen
    </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">
        neveropen
    </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">
        neveropen
    </h1>
    <h3>Explain what is polling in AJAX.</h3>
</body>
<script
 
setInterval(()=>{
  .then((response) => {console.log("response received!")})
},1000)
</script>
</html>


Output: Open the console tab of the browser to see the output.

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments