Search code examples
real-time

Make field data change in real time without refresh.. How on a Website?


I have two numeric fields that contain the following information:

(1) Users Registered (2) Money Raised

Is it possible to make the data change in real time (EVERY SECOND) while someone is viewing the page with the fields? I don't want the viewer to refresh manually to see the updated number, but have the fields change automically while the page is viewed. I want it to be similar to like a text clock that actually shows the seconds counting, etc.

The fields are connected to a database that is constantly changing every second.

Does anyone know if this is possible? Any examples? or Suggestions?

I really appreciate it.

Erik


Solution

  • I guess this is a web application. In this case you would make a request to your server with XMLHttpRequest every second. The field can then be updated with the response. You might also use websockets which open a permanent connection to the server. Unfortunately they are only supported by newer browsers.

    An example for my first proposal with jQuery:

    // This function starts the request and calls success on response.
    var refresh = function() {
      $.ajax({
        url: "/some/path",
        cache: false,
        success: success
      });
    }
    
    // Replaces the contents of the field with your response and
    // triggers refresh() after 1000ms.
    var success = function(data) {
      $(".field").html(data);
      setTimeout(refresh, 1000);
    }
    
    // Starts processing when document is ready.
    $(function() {
      refresh();
    }