Reddy Reddy - 2 years ago 150
Javascript Question

Datatables AJAX Data Source and Custom Pagination actions

I am using Datatables for building the table for my data.

I am passing JSON response from Server side [Java] to JSP and using Datatables js to build the tables in JSP using the same data.

If I pass 100 records, Datatables automatically provides facility to paginate and scroll through the results. But in my case, I always get only 20 records and when I user click on next page, I should call the localServlet to fetch fresh JSON response for next 20records.

So how do I configure Datatable so that whenever pagination function is used, call the AJAX resource and fetch the data and paint it.

Answer Source

There is a sample at

however the code is in PHP. But having a look at it you will see that there request parameters it uses are iDisplayStart and iDisplayLength

You will have to reimplement this in your server side java.

Below is some code I have used (using Stripes)

    Long count = (Long) getContext().getRequest().getSession(true).getAttribute("xbcount");
    if (count == null) {
        count = histDao.getCount();
        getContext().getRequest().getSession(true).setAttribute("xbcount", count);

    DataTableRes res = new DataTableRes (getsEcho(), count, count);

    int rowStartIdxAndCount[] = {getiDisplayStart(), getiDisplayLength()};

    List<HistoryUint> list = histDao.findAll(rowStartIdxAndCount);

And the DAO

public List<HistoryUint> findAll(final int... rowStartIdxAndCount) {
    EntityManagerHelper.log("finding all HistoryUint instances",
            Level.INFO, null);
    try {
        final String queryString = "select model from HistoryUint model";
        Query query = getEntityManager().createQuery(queryString);
        if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
            int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
            if (rowStartIdx > 0) {

            if (rowStartIdxAndCount.length > 1) {
                int rowCount = Math.max(0, rowStartIdxAndCount[1]);
                if (rowCount > 0) {
        return query.getResultList();
    } catch (RuntimeException re) {
        EntityManagerHelper.log("find all failed", Level.SEVERE, re);
        throw re;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download