Real-time data in a grid - better method
Asked Answered
A

1

18

What is for you the better approach for displaying real-time data (Stock Exchange, Weather, ...) in a grid ?
I use this method:

setInterval(function(){
      jQuery("#list1").trigger('reloadGrid');
}, 5000);
Alcoholize answered 5/5, 2012 at 11:8 Comment(0)
E
16

I find your question very interesting. I think the question could be interesting for many other users. So +1 from me.

The usage of setInterval seams me the best way in common browser independent case. One should of cause save the result of setInterval in a variable to be able to use clearInterval to stop it.

One more small improvement would be the usage of [{current:true}] (see the answer for details) as the second parameter of trigger:

var $grid = jQuery("#list1"), timer;

timer = setInterval(function () {
    $grid.trigger('reloadGrid', [{current: true}]);
}, 5000);

It will save selection during the reloading of grid.

Many new web browsers support now WebSocket. So it would be better to use the way in case if the web browser supports it. In the way one can skip unneeded grid reloading in case if the data are not changed on server and prevent permanent pooling of the server.

One more common way seems to me also very interesting. If one would use some kind of timestamp of the last changes of the grid data one could verify whether the data are changed or not. One can either uses ETag or some general additional method on the server for the purpose.

The current success callback of jQuery.ajax which fill jqGrid allows you use to implement beforeProcessing callback to modify the server response, but it's not allows you to stop jqGrid refreshing based on jqXHR.satus value (it would be xhr.status in the current jqGrid code). Small modification of the line of the code of jqGrid would allows you to stop jqGrid refreshing in case of unchanged data on the server. One can either test textStatus (st in the current code of jqGrid) for "notmodified" or test jqXHR.satus (xhr.status in the current jqGrid code) for 304. It's important that to use the scenario you should use prmNames: { nd:null } option and set ETag and Cache-Control: private, max-age=0 (see here, here and here for additional information).

UPDATED: I tried to create the demo project based on my last suggestions and found out that it's not so easy as I described above. Nevertheless I made it working. The difficulty was because one can't see the 304 code from the server response inside of jQuery.ajax. The reason was the following place in the XMLHttpRequest specification

For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content. The user agent must allow author request headers to override automatic cache validation (e.g. If-None-Match or If-Modified-Since), in which case 304 Not Modified responses must be passed through.

So one sees 200 OK status inside of success handler of $.ajax instead 304 Not Modified from the server response. It seems that XMLHttpRequest get back just full response from the cache inclusive all HTTP headers. So I decide to change the analyse of cached data just saving of ETag from the last HTTP response as new jqGrid parameter and test the ETag of the new response with the saved data.

I seen that you use PHP (which I don't use :-(). Nevertheless I can read and understand PHP code. I hope you can in the same way read C# code and understand the main idea. So you will be able to implement the same in PHP.

Now I describe what I did. First of all I modified the lines of jqGrid source code which use beforeProcessing callback from

if ($.isFunction(ts.p.beforeProcessing)) {
    ts.p.beforeProcessing.call(ts, data, st, xhr);
}

to

if ($.isFunction(ts.p.beforeProcessing)) {
    if (ts.p.beforeProcessing.call(ts, data, st, xhr) === false) {
        endReq();
        return;
    }
}

It will allows to return false from beforeProcessing to skip refreshing of data - to skip processing of data. The implementation of beforeProcessing which I used in the demo are based on the usage ETag:

beforeProcessing: function (data, status, jqXHR) {
    var currentETag = jqXHR.getResponseHeader("ETag"), $this = $(this),
        eTagOfGridData = $this.jqGrid('getGridParam', "eTagOfGridData");
    if (currentETag === eTagOfGridData) {
        $("#isProcessed").text("Processing skipped!!!");
        return false;
    }
    $this.jqGrid('setGridParam', { eTagOfGridData: currentETag });
    $("#isProcessed").text("Processed");
}

The line $("#isProcessed").text("Processed"); or the line $("#isProcessed").text("Processing skipped!!!"); set "Processed" or "Processing skipped!!!" text in the div which I used to indicate visually that the data from the server was used to fill the grid.

In the demo I display two grids with the same data. The fist grid I use for editing of data. The second grid pulls the data from the server every second. If the data are not changed on the server the HTTP traffic looks as following

HTTP Request:

GET http://localhost:34336/Home/DynamicGridData?search=false&rows=10&page=1&sidx=Id&sord=desc&filters= HTTP/1.1
X-Requested-With: XMLHttpRequest
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://localhost:34336/
Accept-Language: de-DE
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; LEN2)
Host: localhost:34336
If-None-Match: D5k+rkf3T7SDQl8b4/Y1aQ==
Connection: Keep-Alive

HTTP Response:

HTTP/1.1 304 Not Modified
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 06 May 2012 19:44:36 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 2.0
Cache-Control: private, max-age=0
ETag: D5k+rkf3T7SDQl8b4/Y1aQ==
Connection: Close

So no data will be transferred from the server if the data are not changed. If the data are changed, the HTTP header will be started with HTTP/1.1 200 OK and contains ETag of new modified data together with the page of data itself.

One can refresh the data of the grid either manually using "Refresh" button of the navigator or uses "Start Autorefresh" button which will execute $grid1.trigger('reloadGrid', [{ current: true}]); every second. The page looks like

enter image description here

I marked the most important parts on the bottom of the page with the color boxes. If one loadui: "disable" option then one don't see any changes on the grid at all during the pulling of the server. If one commented the option that one will see "Loading..." div for very short time, but no grid contain will flicker.

After starting of "Autorefreshing" one will see mostly the picture like below

enter image description here

If one would change some row in the first grid, the second grid will be changed in a second and one will see "Processed" text which will be changed to "Processing skipped!!!" text in one more second.

The corresponding code (I used ASP.NET MVC) on the server side is mostly the following

public JsonResult DynamicGridData(string sidx, string sord, int page, int rows,
                                  bool search, string filters)
{
    Response.Cache.SetCacheability (HttpCacheability.ServerAndPrivate);
    Response.Cache.SetMaxAge (new TimeSpan (0));

    var serializer = new JavaScriptSerializer();
    ... - do all the work and fill object var result with the data

    // calculate MD5 from the returned data and use it as ETag
    var str = serializer.Serialize (result);
    byte[] inputBytes = Encoding.ASCII.GetBytes(str);
    byte[] hash = MD5.Create().ComputeHash(inputBytes);
    string newETag = Convert.ToBase64String (hash);
    Response.Cache.SetETag (newETag);
    // compare ETag of the data which already has the client with ETag of response
    string incomingEtag = Request.Headers["If-None-Match"];
    if (String.Compare (incomingEtag, newETag, StringComparison.Ordinal) == 0) {
        // we don't need return the data which the client already have
        Response.SuppressContent = true;
        Response.StatusCode = (int)HttpStatusCode.NotModified;
        return null;
    }

    return Json (result, JsonRequestBehavior.AllowGet);
}

I hope that the main idea of the code will be clear also for people which use not only ASP.NET MVC.

You can download the project here.

UPDATED: I posted the feature request to allow beforeProcessing to break processing of the server response by returning false value. The corresponding changes are already included (see here) in the main jqGrid code. So the next release of jqGrid will include it.

Extracanonical answered 5/5, 2012 at 12:45 Comment(16)
Instead of reload the grid every x seconds, is it not possible to "write" directly in the rows ?Alcoholize
@Bertaud: Sorry, I don't understand what you mean. In any way I suppose that you always use gridview: true option of jqGrid. It follows that the whole grid body will be updated using one operation, by setting innerHTML to the table body. If you would modify many rows or even cells of jqGrid separately it could be many time slowly as the reloading of the whole grid. Moreover if some rows are added or removed the pager have to be modified too. So reloading of the grid seems me the best way.Extracanonical
@Bertaud: You should understand the changing of one element on the page follow to recalculation of position of all other existing elements on the page (reflow). So reducing the number of changes of the page could be the most important for improving performance of the page. See here for example more about minimizing browser reflow.Extracanonical
I am using current:true but not in the trigger. I mean by writing in the rows the use of jQuery("#list1").updateGridRows(s,"id"); with s = array. That could improve the refresh ?Alcoholize
@Bertaud: The method updateGridRows is no more part of jqGrid. It's not supported starting with version 4.0 of jqGrid (see here). You can find it still in grid.addons.js, but the method is not quickly. It uses sequential jQuery.html to update every cell of rows from s ($("#list1").updateGridRows(s);). I would not recommend you to use the method.Extracanonical
Thank you for your advices. That means I cannot do better.Alcoholize
I found this: www.lightstreamer.com/demo/jqgriddemo/Alcoholize
@Bertaud: I found only lightstreamer.com/demo/jqGridDemo. The URL lightstreamer.com/demo/jqgriddemo shows 404 error: "Sorry, but the page you are trying to view does not exist.". The demo uses very old jqGrid 3.5.3 and uses setRowData to update the data. Depend on the number of data which will be updated the way could be very good or very bad. The most important part or the demo is inside of lightstreamer.js. It sent POST request every 0.2-0.3 sec and get the changed data back. In general it's interesting, but is uses lightstreamer solution, so it's not common way.Extracanonical
@Bertaud: I implemented my suggestion to use ETag and modified version of beforeProcessing to optimize reloading of the grid in case of unchanged data on the server. See UPDATED part of my answer. I hope it will be helpful either for you or for another jqGrid user having the same problem.Extracanonical
@Bertaud: You are welcome! It's just so that I have to think about some problem like yours. So I have to write the demo, at least for myself. :-) I posted my suggestion as the feature request.Extracanonical
@Bertaud: My feature request is now included in the main code of jqGrid (see "UPDATED" part of the answer)Extracanonical
@Extracanonical Will $grid.trigger('reloadGrid', [{current: true}]) reload the complete grid, even if there was a change only in the single column of the database table? Or will it reload only the row that changed?Idiotic
@SuhailGupta: $grid.trigger('reloadGrid', [{current: true}]) reloads the whole grid body. The problem is only what do the code exactly, which datatype have the grid, the page size of the grid and many other parts of your exact scenario. The answer is very old and jqGrid have many new features now. In any way if you are sure that only one row is changed and you get the data of the row one can use setRowData method. On the other side the changing of one row of the grid can follow changing position of other row and other HTML elements on the page. So web browser reflow will be done.Extracanonical
@SuhailGupta: Reflow can be expensive. Chening of the whole grid body will be done as one operation in jqGrid: assigning innerHTML to <tbody>. So the time on the client side for changing of one row and the time of changing the whole grid body could be not so different. I have to repeat that the best solution depend on the exact scenario in your application.Extracanonical
@Extracanonical The application will work on intranet. The data is constantly written on to the database, but some values could become constant with time.Idiotic
@SuhailGupta: Sorry, but there are no "the best way" to implement dynamical update of the grid based on changing of data on the server. I wrote you that one have to know a lot of details. The posted answer just shows the main case: one can load the data of the grid very quickly (from intranet which quick database access for example). The code shows how to implement simplest pooling the data with combination with skipping reloading if no changing take place since the latest loading of the grid. One can reload the whole grid on changing if it's quickly enough (small page size of the grid).Extracanonical

© 2022 - 2024 — McMap. All rights reserved.