Search code examples
javascriptjqueryhtmljqgrid

Why does jqGrid not show 2nd page when data is loaded dynamically?


I have prepared a jsFiddle which simulates to load data into jqGrid from an echo page. This is the example:

jqGrid Paging Example (click to run)

$(function() {
  var gridSampleData = [
      { id: 10, firstName: "Jane", lastName: "Doe1"},
      { id: 20, firstName: "Justin", lastName: "Time1" },
      { id: 30, firstName: "Jane", lastName: "Doe2"},
      { id: 40, firstName: "Justin", lastName: "Time2" },
      { id: 11, firstName: "Jane", lastName: "Doe3"},
      { id: 21, firstName: "Justin", lastName: "Time3" },
      { id: 31, firstName: "Jane", lastName: "Doe4"},
      { id: 41, firstName: "Justin", lastName: "Time4" }
    ];
  var rowsPerPage = 4;
  var numRows = gridSampleData.length;
  var pagedData = {
    page:1, total:numRows/rowsPerPage, records: numRows, rows: gridSampleData
  }

  // simulate AJAX request: use echoUrl instead of real web service 
  var jsonData = JSON.stringify(pagedData);
  var echoUrl = '/echo/js/?js=' + jsonData; 

  $("#Grid4").jqGrid({ scroll: false, gridview: true,
    pager: '#pagerGrid4', rowNum: rowsPerPage, viewrecords: true,  
    height: 90, width: 400,
    colNames: ['First name', 'Last name'],
    colModel: [{name: "firstName"}, {name: "lastName"}],
    datatype: "json",
        jsonReader: {
      page: "page",
      total: "total",
      records: "records",
      root: "rows",
      repeatitems: false
        },
    mtype: 'POST',
    url: echoUrl
  });
});

HTML:

<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Canonical jqGrid example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.2/css/ui.jqgrid.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.2/jquery.jqgrid.min.js"></script>


<table id="Grid4"></table>
<table id="pagerGrid4"></table>

Everything looks fine, until you click on the navigation buttons - it will not show you the 2nd page. Why is this? If you load data statically, as grid #4 in this example, it works fine.

Note: I had to use jsFiddle, because StackOverflow currently does not support an echo page in the snippet editor.


Solution

  • It is because in your example you are returning all rows of data but always sending page: 1. Each request the grid makes it's told that it is getting data for page 1 it never gets data for page 2. To make your example work you can set the property loadonce to true as I have done in a fork of your original code. Example Fiddle

    Or you could rework your code to send the first 4 rows and page: 1 and when the request comes for page 2 send the last 4 rows and page: 2