3

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It works. I had to customize my JSON response to include sEcho and iTotalRecords and iTotalDisplayRecords, but it works. datatables.net/usage/server-side

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.