The Comet approach (utilizing long polling) and the status of XmlHttpRequest

Recently, I decided to explore raw XmlHttpRequestObjects along with Comet Long Polling. While typically I would rely on GWT or another framework for this task, I wanted to expand my knowledge in the area.

Here's a snippet of the code I wrote:

function longPoll() {
  var xhr = createXHR(); // Initializes an XmlHttpRequestObject
  xhr.open('GET', 'LongPollServlet', true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {

        if (xhr.status == 200) {
            ...
        }

        if (xhr.status > 0) {
            longPoll();
        }
    }
  }
  xhr.send(null);
}

...
<body onload="javascript:longPoll()">...

To prevent an unnecessary comet call when exiting the page, I enclosed the longPoll() invocation within an if statement checking for status > 0. This adjustment was necessary because I noticed that a final request is made when navigating away from the page or reloading it, causing issues especially in Firefox.

Question: Is verifying the status as I did the most efficient way to address this issue, or are there better alternatives available?

Answer №1

In my opinion, the solution provided is accurate unless proven otherwise.

Answer №2

I really appreciate the straightforward nature of this loop.... I believe that the server-side script needs to pause or continuously check for new data before it's classified as long polling; otherwise, it's just standard polling. It would also be beneficial to implement a mechanism to handle failed requests. Enclosing that process within a try-catch block should resolve any issues.

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

Retrieve() displays solely the initial array within an object

I am facing an issue with my Redux/React project where I am calling an API to search for a specific ID based on the useParams value. I suspect the problem lies in my return statement return data.hero.find(hero => <Hero key={hero.id} hero={hero} /> ...

Issues encountered with registration form functionality (PHP/MySQL)

My form validation and database update seem to have hit a snag. The issue is that the signup() function isn't being triggered when clicking on the "Sign me up" button in home.php (located in the public directory) which links to signup.php (../signup.p ...

Error in jQuery ajax request when passing multiple variables to php script

When I use ajax to send two variables to PHP, the second variable is received correctly, but the first variable is always reported as NULL by PHP. I checked the JavaScript variable before sending it and confirmed that it contains an array of strings. I&apo ...

What is the best way to send this form with jQuery AJAX?

I currently have a PHP email form on my website where users enter their email address and receive a link to the file they uploaded. I would like to enhance this by submitting the form using AJAX for a smoother user experience. At the moment, users click o ...

Troubleshooting React child problems in TypeScript

I am facing a coding issue and have provided all the necessary code for reference. Despite trying numerous solutions, I am still unable to resolve it. export class JobBuilderOptimise extends React.Component<JobBuilderOptimiseProps & JobBuilderOptim ...

What is the optimal approach for managing script initialization on both desktop and mobile devices?

I have implemented a feature on my website that can detect whether the viewer is using a mobile device. Additionally, I have created a JavaScript script that adjusts settings based on whether the user is on a mobile device or not. However, I am wondering ...

After making an Ajax call, Spring controller determines the URL and redirects to a new page

When working on my JSP page, I implement an Ajax post to communicate with my Spring controller. The data that is being posted is used to determine the destination for a redirect call. Here's how the code might look: @RequestMapping(value="/postFromJS ...

Leveraging ng-attr in dynamically added HTML elements through ng-bind-html

Have you ever wondered how ng-attr is evaluated for elements inserted using ng-bind-html? Check out this JS Fiddle demonstration. Here's the HTML: <body ng-app="TestApp" ng-controller="TestCtrl"> <div ng-bind-html='y | to_trusted&a ...

Using JQuery to cycle a class with a timer

My list has the following structure <div id="slider"> <ul> <li class='active'> a </li> <li> b </li> <li> c </li> <li> d </li> <li> e </li> </u ...

Is there a way to include @odataid in an ajax request in order to invoke a post method that assigns an owner to a group?

Seeking assistance on how to utilize ajax for adding an Owner to an O365 group. Utilizing the following endpoint: https://graph.microsoft.com/v1.0/groups/{id}/owners/$ref This is my current ajax call setup, where I am passing user information through the ...

Unraveling complex JSON structures

JSON data is available on a specific URL: { "href":"http:\/\/api.rwlabs.org\/v1\/jobs?limit=10", "time":18, "links": { "self": { "href":"http:\/\/api.rwlabs.org\/v1\/jobs?offset=0&am ...

Tips for sending parameters to XSLT using a Javascript function

Despite my efforts to find a solution in various online posts, I haven't been able to resolve the issue. The challenge lies in my HTML file that includes a JavaScript function for parsing XML and rendering XSLT. I have multiple 'records' in ...

What is the process for developing a personalized search feature in VueJS?

How can I create a custom search function in VueJS that allows me to input partial product names and receive relevant results? For example, I have 2 products named PlayStation Plus 90 Days IE and PlayStation Plus 90 Days NO. Currently, I have to input the ...

A step-by-step guide for invoking a JSON-based API

I'm currently facing an issue with calling a JSON-based authentication API. The API requires two parameters, username and password, to be passed in JSON format. What could be the mistake in my approach? Below is the snippet of my current test code: ...

execute a REST function on the server side from the client side

On the server side, there is an archive named restApi.js containing REST functions. These functions have been tested and work fine with Prompt Command. On the client side, there is an archive named index.ejs, and the goal is to call the REST functions fro ...

Learn how to achieve a sleek animation similar to the famous "Ken Burns effect" by utilizing the CSS property "transform" instead of "object-position". Check out the demo to see it in action!

I am currently exploring how to create an animation similar to the "Ken Burns" effect using CSS transform properties. While I have been using object-position to animate, I am facing challenges with the fluidity of the movement. I am seeking help to achiev ...

Enable/Deactivate Chrome Extension Content Script

I am exploring ways to enable users to toggle a Chrome content script with the click of a button. It appears that using chrome.browserAction is the most efficient method for achieving this. However, when I include the following code snippet: chrome.brow ...

Failure to display updated property value

After rendering an array of objects, I am attempting to add a new property using a function. However, the new property value is not displaying on the page even though it is present when I log the object in the console. The new property that I want to add ...

By invoking the connect() function in Mongoose.js, you can establish several connections to a MongoDB database

In my Node.js Express app, I am establishing a single connection to MongoDB using Mongoose: var express = require('express'); var mongoose = require('mongoose'); mongoose.connect('localhost', 'test'); After definin ...

Display only the requested view - CakePHP

I am looking to display the view independently, without including the <head> and other sections specified in the default.ctp file. The information I need to display is stored in an element: <?php echo $post['Post']['id']; ? ...