jQuery DataTables: “Load more” button

Client-side processing

Example

Highlights

JavaScript

  • Include “Load more” plug-in file

    You need to include plug-in’s JavaScript file after loading jQuery and jQuery DataTables files as shown below:

    
    <script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-pageLoadMore/1.0.0/js/dataTables.pageLoadMore.min.js"></script>
    
  • Control elements

    With dom: 'frt' I hide pagination, page length and information controls. These controls are not needed with “Load more” button.

    If you’re using Bootstrap, Foundation or other frameworks, see dom option for default string for your framework and remove characters p, l and i to hide these controls.

HTML

  • “Load more” button

    Button is initially hidden with inline CSS style display:none. This helps to avoid flickering while resource files are being loaded.

    Later visibility of the “Load more” button is controlled based on availability of the additional data in a callback defined by drawCallback option.

    You can use your own markup for the “Load more” button and style it as needed. Just remember to use button’s ID (btn-example-load-more in my example) in the JavaScript code.

Reloading Data

When you reload your data using ajax.reload() API method, number of records loaded on screen at once is preserved. If you want to reset table page length to default, use page.resetMore() API method as shown below.

Server-side processing

Example

Highlights

Code for server-side processing mode is very similar to code used for client-side processing mode. Therefore everything that has been mentioned above also applies here as well.

There is only one notable difference. You need to use predefined function $.fn.dataTable.pageLoadMore as a value for ajax option and specify URL to your server-side script using url option.

For example:


      ajax: $.fn.dataTable.pageLoadMore({
         url: '/test/0'
      }),      

Optionally, you can specify request method using method option and data to be sent to the server using data option. For example:


      ajax: $.fn.dataTable.pageLoadMore({
         url: '/test/0',
         method: 'POST',
         data: { 
            extraParam: 'extraValue'
         }
      }),      

Known Limitations

  • Plug-in expects data returned by the server-side script to be in data property. For example:

    
    {
        "draw": 1,
        "recordsTotal": 57,
        "recordsFiltered": 57,
        "data": [
            [
                "Angelica",
                "Ramos",
                "System Architect",
                "London",
                "9th Oct 09",
                "$2,875"
            ],
            [
                "Ashton",
                "Cox",
                "Technical Author",
                "San Francisco",
                "12th Jan 09",
                "$4,800"
            ],
            ...
        ]
    }
    

Also please note that I am using Mockjax plug-in to emulate server-side processing in my example. This plug-in (jquery.mockjax.min.js) and corresponding code ($.mockjax({ ... })) is not needed in production.

You May Also Like

Comments

  1. Works great – how we do we trigger a reload of the ajax data externally? So if I want to send a new data object to the server as request body then refresh the table? I’m using search inputs external to datatables.

      1. Thank you for the quick response. There is a problem however, as the table doesn’t clear itself of data before getting a new data set. table.clear().draw() doesn’t seem to work. It does however append the new data on the end of the datatable.

        1. I confirm.
          table.clear().draw() and ajax.reload() do NOT clear the existing data. That initial data is somehow stored in an internal memory, could you please let us know how to fix this?

          1. Please download a new version of the plug-in and try to use page.resetMore() API method to reset the state of the “Load more” plug-in before using ajax.reload(). There was a bug in that API method in version 1.0.0 and I just updated the plug-in to 1.0.1. Please see this example for code and demonstration.

                1. Hi Michael,
                  page.resetMore() doesn’t work properly in server-side. it doesn’t clear rows, but keeps appending new rows. I am using your latest version of `Load more` plug-in 1.0.1 and datatable 1.10.16. After suffering for a couple of hours, I decided to take a look at your source codes and I found that there’s no chance to clear cache in your code.
                  Please review my pull request and merge it so others could avoid the same issue 🙂

        2. Later: The problem seems to occur only when using $.fn.dataTable.pageLoadMore. After removing it, the table gets properly cleared. However, this brings another issue: after loading more results and applying filters again/reseting filters (ajax, server side), the length remains to that length of 20-30-n results. My solution is to use:
          table.page.len( 10 ).clear().draw();

  2. Thank you for these examples.
    Can you please tell us how to choose how many records to be loaded at one time? I see you get 10. For me, the whole ajax dataset is loaded. How can I limit this?

  3. Very good plugin. Like costel, I am also only getting the entire dataset to load at once. I’ve got “paging”: true, “pagelength”: 10 currently set in my code – is it possible that something else is interfering? I’ve also got column filtering and column sort on one column also active.

      1. I’m not sure, I’ve just created a second page, db-test2.php which is running your plugin and connected to the same db-connect.php file (db-test.php has reverted to the original settings and now only returns a 20 result page). I’ll keep looking though.

        1. The problem is in your server-side script db-connect.php. It disregards request to return limited number of records and returns everything. I recommend using ssp.class.php class from DataTables distribution for server-side processing. Please see github.com for more details.

  4. Hi Michael, I got it up and running by changing to ssp.class.php, thanks. I’ve noticed that search doesn’t work for me or on your server-side example – I presume this is a known limitation?

    1. Search doesn’t work in my server-side example because it’s hard to emulate server-side processing with jsFiddle. But it should work with ssp.class.php if implemented correctly.

    1. Oh, there is one thing from me, sir. For the server side processing, the column sorting is doesn’t work.
      Can you give me some advice, sir? Thank you.

  5. I am trying to use “load more” functionality in my example, but it’s not showing “load more” button.
    I am loading data from aspx page using Ajax. Please help.

     $('#example').DataTable(
        {
           
            
            "ajax":
                {
                    "url": "Default.aspx/GetData",
                    "contentType": "application/json",
                    "type": "GET",
                    "dataType": "JSON",
                   
                   
                    "data": function (d) {
                        
                        return d;
                    },
                    "dataSrc": function (json) {
                      
                        json.draw = json.d.draw;
                        json.recordsTotal = json.d.recordsTotal;
                        json.recordsFiltered = json.d.recordsFiltered;
                        json.data = json.d.data;
    
                        var return_data = json;
                        return return_data.data;
                    }
                    
                },
            "columns": [
                        { "data": "Cemetery" },
                        { "data": "Contact" },
                        { "data": "County" },
                        { "data": "Address" }
                       
            ]
        });
    });
    
  6. Thank you Michael for your example. I am trying to create a hyperlink for one of the columns via the “render” function like so, but it does not work. Can you tell me please, where should I place the render function in your example? Thank you in advance!:

    
                                    "columns": [					 
    					{ "data": "weblink",
    						"render": function(data, type, row, meta){
    							if(type === 'display'){
    								data = '<a href="' + data + '" rel="nofollow">' + data + '';
    							}            
    							return data;
    						}
    					},
    					{ "data": "information" }
    				]
    

    The JSON string looks like this (modified from your raw AJAX example to include column identifiers):

    {    
        "draw": 1,
        "recordsTotal": 57,
        "recordsFiltered": 57,
        "data":[
    		[			
                            "weblink": "http://www.microsoft.com",
                            "information": "THIS IS SERVER SIDE",
    			"information": "System Architect",			
    			"information": "5421",
    			"information": "2011/04/25",
    			"information": "$320,800"
               
    		],
    		[
            	        "weblink": "http://www.yahoo.com",
    			"information": "Garrett Winters",
    			"information": "Accountant",			
    			"information": "8422",
    			"information": "2011/07/25",
    			"information": "$170,750"           
    		]
    	]
    }
    
      1. Michael, that was a super-fast reply dude, thank you! Your validated JSON fixed my problem…and thank you for sharing the validator link. Cheers my friend!

  7. Good morning Michael. I cannot post my code, for some reason I keep receiving a 403 Forbidden error.

    I have a couple general questions:
    1) Would you mind sharing an example of how I can pass back a single key value that I have available from my server page (in addition to the column data I’m already successfully passing) in JSON?
    2) How to use that returned value to set a hidden form field for later use.
    3) How to pass that hidden form field value back to the server page via your “Load More”.

    I have code attempts for all of this, but I cannot post code today for some reason. I may just be special, my apologies.

    Thanks in advance!

  8. I am trying to add this to the post method data string:
    extraParam: document.getElementById(‘hold_LoadMoreID’).value

    Where might I be going wrong? Thanks!

  9. Hello Michael Ryvkin

    can You give me example load more on Scroll. i try many time but my badluck. then after i see your example but in your example you did load more on button i need load more on scroll. how can i do??

  10. Top plugin!!! Works like a charm!

    Perfect for an infinite scroll with server processing pagination!

    Thank you very much.

  11. My website in PHP but I am unable to implement this code with my site.
    Please let me know how can I do it?

  12. how do I make this code work with datatable returned from c# controller with data send as json , i’m getting 

    “uncaught TypeError: Cannot read property ‘length’ of undefined” 

    1. This error usually means that DataTables cannot find the data in the response. ASP.NET methods wrap all of their Ajax responses with {d: [response]}. If you’re using client-side processing mode and default data structure, you can use DataTables option "dataSrc": "d.data" to resolve the issue. For server-side processing mode, see this answer on StackOverflow.

Leave a Reply

(optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.