Rendering real-time data using jQuery's Ajax functionality

Imagine having a webpage that gradually returns a large amount of data over time. Here's an example code snippet to illustrate this:

<?php

$iTime = time();

while(time()-$iTime < 10 ) {
    echo "Hello world";
    echo str_repeat( ' ', 1024 ) . "<br />";
    flush( );
    sleep(3);
}

?>

The goal is to display all incoming data in real-time, updating the content as it arrives. Essentially, once a line of data is sent, it should be parsed and displayed immediately.

Can this be achieved using jQuery? Any guidance would be greatly appreciated.

Thank you for your assistance! :)

Answer №1

Creating a basic comet-style long poll is actually quite simple:

PHP:

<?php
    $data = null;
    while ($data ==  null)
    {
         $data = find_data($_REQUEST['last_update']); // This part is customizable.
         sleep(5);
    }
    echo json_encode($data);

JavaScript:

 function setListener()
 {
      $.ajax({
           url: 'updater.php',
       dataType: 'json',
       success: function(data, status, xhr) 
           {
              // Perform actions with the received data.
              setListener();
           },
       error: function()
           {
               setTimeout(setListener,10000);
           }
       });
 }

Answer №2

Check out the ajax-http-stream jQuery plugin. This plugin enhances jQuery ajax calls to handle comet-style data streaming from the server and triggers a function called OnDataReceived whenever new data is received.

Answer №3

It seems like you've reached the limitations of the HTTP protocol itself, which means this is more about web programming than just jQuery. If you're looking for real-time push functionality, consider using a different protocol like XMPP (which big players like Google Wave use).

When working with jQuery, my suggestion would be to implement normal polling on efficient, low-power resources. You can easily create static resources that utilize HTTP caching effectively and follow principles of REST. For example:

  1. setTimeout('myPoll("http://my_feed")', 500);
  2. Ensure my_feed uses HTTP caching as a static method (perhaps personalized per user if necessary)

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

The issue of dynamic select not sending the POST data

Having an issue with a form where the selected country and city are not being posted correctly. Despite different names in the form and php mailer script, both selections are coming through as the country. Here's the form: <select style="width: 6 ...

Toggle button color on click by using ng-click on a different button

As a newcomer to Angular, I am facing an issue. I have two buttons - button1 and button2. What I want is that when I click on button1, its color changes from green to red. Then, when I click on button2, the color of button1 should revert back to green. How ...

Triggering an automatic pop-up window using JavaScript based on a PHP condition

I have developed a hidden pop-up box that becomes visible when targeted, with its opacity increasing to one. I am aiming for the pop-up to appear if the user is identified as a "firstTimeUser," a status saved in a PHP $_SESSION variable. However, I am stru ...

How can I prevent event propagation in Vuetify's v-switch component?

Currently, I am working with Vuetify and have incorporated the use of v-data-table. Whenever I click on a row within this data table, a corresponding dialog box represented by v-dialog should open. Additionally, each row contains a v-switch element. Howeve ...

Returning a 404 Error stating "Invalid request to /api/users/register."

Encountering an issue with proxy connection - unable to determine the root cause despite verifying all routes. Not able to successfully register the user and store data in MongoDB. Seeking suggestions for resolution. Thank you. Attempting to send user reg ...

Store the image URL in cache during AJAX loading

I have implemented an ajax slider to display images, and it is functioning perfectly. However, I am facing an issue with image caching. Since the images change dynamically using ajax, there is no cache available which causes a delay in displaying the new i ...

Implementing JavaScript logic to proceed to the following array within a 3D array once a specific condition is met

I'm currently tackling a challenge that requires me to obtain a specific number using a given 3D array. This array consists of 2D arrays, each containing the same number repeated x times. The parent array is sorted from largest to smallest. Here&apos ...

How can we avoid repeated evaluations by using memoization in a function?

Currently, I am working on a jQuery function designed to switch HTML elements based on specific viewports. The concept is quite simple: <div data-swap-for="#element" data-swap-on="phone"></div> This code snippet will insert the element with t ...

Filling an HTML template with an $http response in VueJS

After learning about VueJs, I decided to embark on a small project - a nutrition app where food recommendations are made based on specific nutrients. Below is the JavaScript code snippet: recommendFood: function() { this.recs = {}; ...

What is the proper way to define the routes for an ajax button_to?

I have successfully integrated an ajax-powered button to manage adding and removing a calendar event from a user's "wish list". The button performs as a toggle-switch, allowing users to add events if they are not already on the wish list, and remove t ...

Is there a way to retrieve data from a sealed JSON object using JavaScript?

The data is being fetched from the API and here is the response object: { "abc": [{ "xyz": "INFO 1", "pqr": "INFO 2" }, { "xyz": "INFO 3", "pqr": "INFO 4" } ] } We are lookin ...

Significant delay in processing second jQuery Ajax call

Attempting a simple Ajax call with page content refresh using the following code snippet: $("a.ajaxify-watched").bind("click", function(event) { $item = $(this); $.ajax({ url: $(this).attr("href"), global: false, type: "G ...

What is the method to invoke a function within a factory in angularjs by using a string parameter?

I have a complex logic that I want to encapsulate in an AngularJS factory for easy use with dependency injection. The challenge is that the logic is dynamic, so I don't know in advance what functions will be available. What I have is a string represen ...

Tips for Implementing {{ }} within Angular Filters in Nested ng-repeat statements

I am looking to incorporate {{ }} within the Angular "filter" filter, specifically while nested inside an ng-repeat. Let's consider the relationship below: var categories = [ {"title":"land"}, {"title":"sea"}, {"title":"air"} ]; var vehi ...

The code functions perfectly on JSfiddle, but for some reason it halts when implemented on

Unfortunately, the code that was working perfectly on JSfiddle seems to be encountering issues when implemented on a regular HTML site. The content loads fine but there seems to be an error with the preview function after selecting an image. We have colla ...

Generating intricate JSON structures with JavaScript programming instructions

In the world of JSON, I am still a novice. I need to use JavaScript to construct the JSON structure below, but I'm struggling with adding the second element ("12101") and populating the people in the JSON Structure. Below is the code I tried, however, ...

Is it possible for me to pass a value through props that is not currently stored in the state?

Within the realm of Reactjs, imagine a scenario where there exists a <Parent> component containing state and a variable named foo, which is either 'global' or local to Parent. The question arises: Can we pass foo as props using <Child v ...

Tips for modifying the href attribute when a user clicks

Is there a way to dynamically change the value of this link <a href="/Countries/388/10">next</a> without having to refresh the page? For example, if a user clicks on the link, it should update to <a href="/Countries/388/20">next</a&g ...

Transmit progress updates while an Ajax request is in progress

Imagine we have an Ajax call. Here's an example: function delete_mov(id){ $.ajax("delete_mov.php?id="+id ) .success(function(){ $('#message').("Movimento "+id+" correttamente cancellato"); }) .fail(function(){ ...

Unexpected Actions from AJAX response in JSON format

When I make a request to the server and receive an object, it looks like this: $(document).ready(function () { var req= $.getJSON("api/Appointments"); req.done(function (data) { $.each(data, function (key, value) { ...