"Exploring the transition from traditional polling to the enhanced experience

I have a script that utilizes basic polling to display the total number of records in the database in real-time.

Can anyone provide an example of converting my code into a long polling structure using plain JavaScript? I've searched on Google but all the results show jQuery examples, which I find difficult to adapt to my situation. Here is a .gif screenshot showing my code in action for better understanding:

https://i.sstatic.net/pS0tV.gif

Below is my basic polling example code that needs to be transformed into long polling:

index.php

<style>
    #label{
    margin: 0;
    color: red;
    font-weight: bold;
    }
</style>

<script>
document.addEventListener('DOMContentLoaded',function(){

/**********************************************************************
Check for a new record amount in the data base
**********************************************************************/

function checkForNewRecords(){

var xhr= new XMLHttpRequest();

xhr.onreadystatechange= function(){

if(xhr.readyState == 4){
document.querySelector('#output').innerHTML= xhr.responseText;

}
}

xhr.open('POST','check-for-new-records.php');
xhr.send();  

}

setInterval(function(){checkForNewRecords()},1000);

});
</script>

<p id='label'>Total records in the database in real time in basic polling</p>

<div id='output'></div>

check-for-new-records.php

<?php

$db_servername= 'localhost';
$db_username='jd';
$db_password= '1234';
$db_name= 'test';

$db_connect= new mysqli($db_servername,$db_username,$db_password,$db_name);

$db_query= "SELECT COUNT(id) AS id FROM example";

$db_result= $db_connect->query($db_query);
$db_row= $db_result->fetch_object();

$total_records= $db_row->id;

?>

<style>
#total-records{
margin-top: 0;
}
</style>

<p id='total-records'><?php echo $total_records; ?></p>

I am looking to convert this into long polling with just plain JavaScript. Please avoid suggesting alternative methods as I am focused only on this specific conversion. It seems challenging to find help online regarding plain JavaScript solutions compared to the abundance of jQuery examples available. Not everyone prefers using libraries, and I have been disappointed by the lack of helpful responses on this particular topic. Your input would be greatly appreciated.

Answer №1

Avoid using setInterval; opt for setTimeout instead.

The key distinction between polling and long polling lies in the timing of server response. With polling, the server responds immediately, prompting the client to wait a specified period before sending the next request. In contrast, long polling involves the server withholding its response until new data is available or a timeout occurs, at which point the client promptly submits another request.

Whether utilizing XMLHttpRequest, fetch, or jQuery, the implementation remains consistent – differing only in the delay imposed on subsequent requests by the client side.

Polling:

function checkForNewRecords() {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
      document.querySelector('#output').innerHTML = xhr.responseText;

      setTimeout(checkForNewRecords, 1000); // Polling involves delay on the client side
    }
  }

  xhr.open('POST', 'check-for-new-records.php');
  xhr.send();

}

checkForNewRecords()

Long-Polling:

function checkForNewRecords() {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
      document.querySelector('#output').innerHTML = xhr.responseText;

      setTimeout(checkForNewRecords, 0);
      // Long-polling incurs delay on the server 
      //The client triggers a new request immediately after receiving a response.
    }
  }

  xhr.open('POST', 'check-for-new-records.php');
  xhr.send();

}

checkForNewRecords()

Server-side adjustments are typically required to optimize long polling efficiency.

The primary disparities between polling and long polling pertain to optimization strategies for signaling the server when to dispatch update notifications. However, this factor is entirely distinct from the method used to request data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Javascript - Execute function after all nested forEach loops have finished running

I'm finding this task to be quite challenging, as I am struggling to comprehend it fully at the moment. The issue involves nested forEach loops, and I require a callback function to execute once all the loops have finished running. I am considering u ...

Error in background request for Chrome app/extension, or problem allowing app to access Google Docs API

I'm encountering an issue where the Google Doc API is not allowing a desktop application to be installed, although this worked fine in Chrome 27.0 previously. Below is my Manifest.Json file: { "name": "__MSG_extName__", "description": "__MSG_ext ...

Behavior of routing not functioning as anticipated

In my app-routing.module.ts file, I have defined the following routes variable: const routes: Routes = [ { path: '', redirectTo: '/users', pathMatch: 'full' }, { path: 'users', component: UsersComponent }, ...

The functionality of AJAX seems to be experiencing glitches after relocation on the local server

I'm having an issue with my testing code that was working fine on the remote server but started causing problems when I moved it to localhost using XAMPP. The page in question is located at: http://localhost/test/test.php <!DOCTYPE html PUBLIC " ...

How to use JavaScript regular expressions to verify that an input contains more than zero characters

Can someone help me with a simple regex issue? I've tried searching online but couldn't find a suitable example. I'm struggling with regex and just need to ensure that an input contains more than 1 character (i.e. is not blank). My code uses ...

Utilizing the 'PUT' update technique within $resource

Hey there, I'm pretty new to Angular and looking for some guidance on how to implement a PUT update using angular $resource. I've been able to figure it out for all 'jobs' and one 'job', but I could use some assistance with in ...

React's Conditional Rendering

Let's imagine having these initial conditions: this.state = {plans: [], phase: 'daybreak'} along with a dynamic JSON object fetched from an API containing various schedules that may change periodically, for example: plans = {"daybreak": " ...

Tips for utilizing Mailchimp for sending emails using AJAX

Is there a way to send emails using the Mailchimp API through AJAX? I've searched through the documentation but haven't found any information on integrating Mailchimp with JQuery. ...

Adjusting the size of a Youtube iframe when the superview is modified with WKWebview

While working with a WKWebview that has an embedded YouTube video using their JS SDK, I encountered an issue. My setup includes three different views - internal container, full-screen container, and external (airplay mirroring) container where the WKWebvie ...

My objective is to show the div element just once using AngularJS

Here's the scenario I want to show this div just once, not multiple times: //angular js code $scope.arr=["sunday","mpnday","tuesday"]; //html view <ul> <li ng-repeat="x in arr"> <div><p>{{ x }}</p> </div> & ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

What is the code to programmatically select a checkbox in an ExtJS treepanel when a button is clicked?

I am working with an Extjs treepanel that has several layers added to it. Additionally, I have a search panel with a search button. Clicking on the search button displays the results in an extjs gridview. My goal is to show layers by clicking on a row in ...

Tips for sending a variable to control a particular panel within an accordion in Angular 2

I have a collection of ngbpanels that are dynamically created using ngFor. I need to expand or collapse a specific panel based on certain conditions, but the ID I provide for the panel is stored in a variable. The code does not recognize the panel ID when ...

Failed to fetch http://localhost:8000/Stack/script.js due to network error 404 in Django project

As I embark on creating a simple to-do app, I encountered an error while trying to implement some JavaScript on the homepage. The error in question is highlighted above (Get http://localhost:8000/Stack/script.js net:: Err_Aborted 404). Being new to integra ...

Page reloads are disabled when Chrome devtools debugger is paused in a React app

Currently, I am in the process of troubleshooting a React application that was created using create-react-app. Whenever I attempt to reload the page while paused on a breakpoint, it results in the page stalling. The screen goes blank and is unresponsive t ...

Error: Unable to access properties of an undefined value (trying to read 'type') within Redux Toolkit

Looking for help with this error message. When trying to push the book object into the state array, I encounter an error. Folder structure https://i.stack.imgur.com/9RbEJ.png Snippet from BookSlice import { createSlice } from "@reduxjs/toolkit" const ...

Manipulating and filtering an array of objects in JavaScript/jQuery

Looking to simplify my array manipulation in Javascript, I need to subset based on key-value matches. I have an array called js_obj, and my goal is to modify objects where a certain condition is met. Consider the structure of my array: js_obj = [{ wo ...

Troubleshooting issues with Vue CLI 4 and A-Frame: Finding solutions for

Recently, I've been working on creating a VR web app using Vue cli 4.2.3 and aframe.io. However, I encountered numerous error messages related to aframe's components. [Vue warn]: Unknown custom element: <a-scene> - did you register the com ...

Instructions on accessing the subsequent li a starting from a designated location

My goal is to change the link color of the button with the id #idIMMUNOLOGY_9, which has the class .active_default, but I must start from the element with the id #idTERRITORIAL_8. I attempted this approach : $('#idTERRITORIAL_8').parent().find( ...

The functionality of closing the image on a model popup is not functioning properly following a postback

I am encountering an issue with my ajax modelpopup extender in my webform. The CancelControlID is set to an image called imgClose. When I click on imgClose after the popup has been displayed, it successfully closes the popup. However, if I click on any co ...