Loading data in background

In practice often there is a need to load a couple of data locally and work with it. Usually loading a lot of data locally make the page to load slow and in case of other processes the result is very slow loading of the entire page and hence not happy users.

Fortunately we can use some tricks to speed the process of loading the data of the grid. The idea is very simple – load initially a small piece of data and after that to call in background  ajax to get all the data and put it into the grid, which will be not mentioned by the end user.

In a standard code to load all the data in the grid at once and use it on the grid has the following settings

[js]
$("#grid").jqGrid({

// url to load all the data at once
url: "alldataurl",
datatype : :"json"
// loadd all the data locally and make it available
// set the datatype to local
loadonce : true,

[/js]

Using this approach causes the grid to get all the data, put it on the grid and continue to add the rest of data – rowNum parameter to the local array. This causes in some cases a lost of time when loading the grid initially into the page.

With the idea that we mentioned above initially we will load by example 10 records and then when the data is loaded to use a ajax call to get all the data and put it in the grid local array. This way the process will not mentioted by the user, but we will have all the data.

For calling the ajax we will use the gridComplete event and we will check if the data is loaded in order to prevent every time to make ajax call when we do paging and sorting. Additionally we will define a global variable loaded in order to check if the data if already in the grid local array.

Below is the code snippet with comments which explain the code.
 
[js]
var loaded = false;
$(document).ready(function () {

$("#jqGrid").jqGrid({
// url to load initially 10 records
url: ‘grid.php’,
rowNum : 10,
datatype: "json",

gridComplete : function() {
// if the all the data is not loaded
if(!loaded) {
// set the datatype to local
this.p.datatype=’local’;
var ts = this;
$.ajax({
"url": "grid.php",
"dataType" : "json",
// instruct the server to get all the data with the same sortining
"data" : { oper: ‘grid’, page:1, totalrows : -1, sidx : ‘CustomerID’, sord : ‘asc’ },
success :function( resp ) {
// when loaded simple attach the response data to data array
ts.p.data = resp.rows;
// refresh the indexes
ts.refreshIndex();
// mark that the data is loaded in order no to do it again
loaded = true;
}
});
}

});

});
[/js]

This way we have all the data loaded at a 10 records time.

The working example with code can be seen here

Enjoy

Stay connected with us in your favorite flavor!