Martin Spa
Martin Spa

Reputation: 1534

Custom REST datasource with jQuery DataTables

I have a REST endpoint with a page and size parameter:

http://someservice.com/api/accounts/10/0

In this example it returns the first page and every page has 10 records.

Now, I want to use DataTables, and found this example on StackOverflow, where I can add the data to the table from the REST response to the table.

But, this way, I add all the data to the table. I want to be able to add the data page per page, and make requests to the endpoints page per page. For example, on page load, I make a REST request for that page. When I click to the second page, I make a request again, for the data for that one.

Any way to do this in DataTables?

Upvotes: 3

Views: 3945

Answers (1)

Smiter
Smiter

Reputation: 1391

This should work:

     function fnGetKey( aoData, sKey ){
         for ( var i=0, iLen=aoData.length ; i<iLen ; i++ ){    
            if ( aoData[i].name == sKey )
               return aoData[i].value;        
         }
     return null;
     }

     $('#example').dataTable( {
      "bServerSide" : true,
      "sAjaxSource" : "http://someservice.com/api/accounts/10/0", //first page
      "sPaginationType": "two_button",
      "fnServerData": function ( sSource, aoData, fnCallback ) {
          var startIndex = fnGetKey(aoData, "iDisplayStart")
          var length = fnGetKey(aoData, "iDisplayLength")
          sSource="http://someservice.com/api/accounts/"+length+"/"+(startIndex/length + 1)
          $.getJSON( sSource, aoData, function (json) { 
              fnCallback(json)
          } );
       }
    });

So when you click on next page or previous, you need to calculate at what page you are now and by changing source you do a trick.

Upvotes: 3

Related Questions