I have a jqGrid that points at an external API, which I have no control over. This external API has two endpoints:
- Data Endpoint - Returns the table row data
- Count Endpoint - Returns pagination counts etc.,
Based on user input the jqGrid filter gets converted into the appropriate query-string to filter the external API's Data and Count Endpoints.
I have jqGrids url
being dynamically built based off of user input and targets the Data Endpoint...and during the loadBeforeSend()
event it calls the Count Endpoint to get the latest pagination information based on users filter.
I am using the jsonreader capabilities:
jsonReader: {
root: 'products',
id: 'id',
records: function () {
return gridTotal;
},
total: function () {
// var totalPages = (gridTotal + reqOptions.limit-1) / reqOptions.limit;
var totalPages = Math.ceil(gridTotal / reqOptions.limit);
console.log('totalPages: ' + totalPages);
return totalPages;
},
page: function () {
//var totalPages = Math.ceil(gridTotal/20);
console.log('currentPage: ' + reqOptions.page);
return reqOptions.page;
}
},
Sample of the loadBeforeSend method:
loadBeforeSend: function (xhr, settings) {
settings.url = _newUrl || endpointURL;
// Lets fetch our data count...this may change as items get published so lets fetch during load
products.count(accessToken, _filterQuery)
.success(function (resp) {
// This is the total number of products that match our current search
gridTotal = resp.count;
}).catch(function (err) {
console.error(err);
});
}
Fetching from the Data Endpoint works really well, the issue is how to call the Count Endpoint and update the pagination data.
Tried the following:
- Using
setGridParam
for records, last_page, etc., - Using
getGridParam('reccount')
- Just update the html to look correct (not effective since paging will be off)
Is there a way to
- Manually fire off the XHR for jqgrid URL...so I can request the Count first and when it returns then go fetch the Data?
- Rerun the jsonreader functionality once the Count returns and
gridTotal
is set - Use a promise like structure to resolve records count
Updated to show @Oleg solution
loadBeforeSend: function (xhr, settings) {
settings.url = _newUrl || endpointURL;
// Lets fetch our data count...this may change as items get published so lets fetch during load
products.count(accessToken, _filterQuery)
.success(function (resp) {
// This is the total number of products that match our current search
gridTotal = resp.count;
gridTotal = resp.count;
grid.jqGrid('setGridParam', {
page: gridOpts.jsonReader.page(),
records: gridTotal,
lastpage: gridOpts.jsonReader.total()
});
grid[0].updatepager(false, true);
}).catch(function (err) {
console.error(err);
});
}