Data Tables and DataTables Plugin in jQuery 1.3 with PHP

by Kae Verens | October 2009 | MySQL Content Management Open Source PHP Web Development

In this article by Kae Verens, we will look at:

 

  • How to install and use the DataTables plugin
  • How to load data pages on request from the server
  • Searching and ordering the data

From time to time, you will want to show data in your website and allow the data to be sorted and searched.

It always impresses me that whenever I need to do anything with jQuery, there are usually plugins available, which are exactly or close to what I need.

The DataTables plugin allows sorting, filtering, and pagination on your data.

Here's an example screen from the project we will build in this article. The data is from a database of cities of the world, filtered to find out if there is any place called nowhere in the world:

Data Tables and DataTables Plugin in jQuery 1.3 with PHP

Get your copy of DataTables from http://www.datatables.net/, and extract it into the directory datatables, which is in the same directory as the jquery.min.js file.

What the DataTables plugin does is take a large table, paginate it, and allow the columns to be ordered, and the cells to be filtered.

Setting up DataTables

Setting up DataTables involves setting up a table so that it has distinct < thead > and < tbody > sections, and then simply running dataTable() on it.

As a reminder, tables in HTML have a header and a body. The HTML elements < thead > and < tbody > are optional according to the specifications, but the DataTables plugin requires that you put them in, so that it knows what to work with.

These elements may not be familiar to you, as they are usually not necessary when you are writing your web pages and most people leave them out, but DataTables needs to know what area of the table to turn into a navigation bar, and which area will contain the data, so you need to include them.

Client-side code

The first example in this article is purely a client-side one. We will provide the data in the same page that is demonstrating the table.

Copy the following code into a file in a new demo directory and name it tables.html:

<html> 
<head>
<script src="../jquery.min.js"></script>
<script src="../datatables/media/js/jquery.dataTables.js">
</script>
<style type="text/css">
@import "../datatables/media/css/demo_table.css";</style>
<script>
$(document).ready(function(){
$('#the_table').dataTable();
});
</script>
</head>
<body>
<div style="width:500px">
<table id="the_table">
<thead>
<tr>
<th>Artist / Band</th><th>Album</th><th>Song</th>
</tr>
</thead>
<tbody>
<tr><td>Muse</td>
<td>Absolution</td>
<td>Sing for Absolution</td>
</tr>
<tr><td>Primus</td>
<td>Sailing The Seas Of Cheese</td>
<td>Tommy the Cat</td>
</tr>
<tr><td>Nine Inch Nails</td>
<td>Pretty Hate Machine</td>
<td>Something I Can Never Have</td>
</tr>
<tr><td>Horslips</td>
<td>The Táin</td>
<td>Dearg Doom</td>
</tr>
<tr><td>Muse</td>
<td>Absolution</td>
<td>Hysteria</td>
</tr>
<tr><td>Alice In Chains</td>
<td>Dirt</td>
<td>Rain When I Die</td>
</tr>
<!-- PLACE MORE SONGS HERE -->
</tbody>
</table>
</div>
</body>
</html>

When this is viewed in the browser, we immediately have a working data table:

Data Tables and DataTables Plugin in jQuery 1.3 with PHP

Note that the rows are in alphabetical order according to Artist/Band. DataTables automatically sorts your data initially based on the first column.

The HTML provided has a < div > wrapper around the table, set to a fixed width. The reason for this is that the Search box at the top and the pagination buttons at the bottom are floated to the right, outside the HTML table. The < div > wrapper is provided to try to keep them at the same width as the table.

There are 14 entries in the HTML, but only 10 of them are shown here. Clicking the arrow on the right side at the bottom-right pagination area loads up the next page:

Data Tables and DataTables Plugin in jQuery 1.3 with PHP

And finally, we also have the ability to sort by column and search all data:

Data Tables and DataTables Plugin in jQuery 1.3 with PHP

In this screenshot, we have the data filtered by the word horslips, and have ordered Song in descending order by clicking the header twice.

With just this example, you can probably manage quite a few of your lower-bandwidth information tables. By this, I mean that you could run the DataTables plugin on complete tables of a few hundred rows. Beyond that, the bandwidth and memory usage would start affecting your reader's experience. In that case, it's time to go on to the next section and learn how to serve the data on demand using jQuery and Ajax.

As an example of usage, a user list might reasonably be printed entirely to the page and then converted using the DataTable plugin because, for smaller sites, the user list might only be a few tens of rows and thus, serving it over Ajax may be overkill. It is more likely, though, that the kind of information that you would really want this applied to is part of a much larger data set, which is where the rest of the article comes in!

Getting data from the server

The rest of the article will build up a sample application, which is a search application for cities of the world.

This example will need a database, and a large data set. I chose a list of city names and their spelling variants as my data set. You can get a list of this type online by searching.

The exact point at which you decide a data set is large enough to require it to be converted to serve over Ajax, instead of being printed fully to the HTML source, depends on a few factors, which are mostly subjective. A quick test is: if you only ever need to read a few pages of the data, yet there are many pages in the source and the HTML is slow to load, then it's time to convert.

The database I'm using in the example is MySQL (http://www.mysql.com/).

It is trivial to convert the example to use any other database, such as PostgreSQL or SQLite.

For your use, here is a short list of large data sets:

The reason I chose a city name list is that I wanted to provide a realistic large example of when you would use this.

In your own applications, you might also use the DataTables plugin to manage large lists of products, objects such as pages or images, and anything else that can be listed in tabular form and might be very large.

The city list I found has over two million variants in it, so it is an extreme example of how to set up a searchable table.

It's also a perfect example of why the Ajax capabilities of the DataTables project are important. Just to see the result, I exported all the entries into an HTML table, and the file size was 179 MB. Obviously, too large for a web page.

So, let's find out how to break the information into chunks and load it only as needed.

Client-side code

On the client side, we do not need to provide placeholder data. Simply print out the table, leaving the < tbody > section blank, and let DataTables retrieve the data from the server.

We're starting a new project here, so create a new directory in your demos section and save the following into it as tables.html:

<html> 
<head>
<script src="../jquery.min.js"></script>
<script src="../datatables/media/js/jquery.dataTables.js">
</script>
<style type="text/css">
@import "../datatables/media/css/demo_table.css";
table{width:100%}
</style>
<script>
$(document).ready(function(){
$('#the_table').dataTable({
'sAjaxSource':'get_data.php'
});
});
</script>
</head>
<body>
<div style="width:500px">
<table id="the_table">
<thead>
<tr>
<th>Country</th>
<th>City</th>
<th>Latitude</th>
<th>Longitude</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>

In this example, we've added a parameter to the .dataTable call, sAjaxSource, which is the URL of the script that will provide the data (the file will be named get_data.php).

Server-side code

On the server side, we will start off by providing the first ten rows from the database.

DataTables expects the data to be returned as a two-dimensional array named aaData.

In my own database, I've created a table like this:

CREATE TABLE `cities` ( 
`ccode` char(2) DEFAULT NULL,
`city` varchar(87) DEFAULT NULL,
`longitude` float DEFAULT NULL,
`latitude` float DEFAULT NULL,
KEY `city` (`city`(5))
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Most of the searching will be done on city names, so I've indexed city.

Initially, let's just extract the first page of information. Create a file called get_data.php and save it in the same directory as tables.html:

<?php 
// { initialise variables
$amt=10;
$start=0;
// }
// { connect to database
function dbRow($sql){
$q=mysql_query($sql);
$r=mysql_fetch_array($q);
return $r;
}
function dbAll($sql){
$q=mysql_query($sql);
while($r=mysql_fetch_array($q))$rs[]=$r;
return $rs;
}
mysql_connect('localhost','username','password');
mysql_select_db('phpandjquery');
// }
// { count existing records
$r=dbRow('select count(ccode) as c from cities');
$total_records=$r['c'];
// }
// { start displaying records
echo '{"iTotalRecords":'.$total_records.',
"iTotalDisplayRecords":'.$total_records.',
"aaData":[';
$rs=dbAll("select ccode,city,longitude,latitude from cities
order by ccode,city limit $start,$amt");
$f=0;
foreach($rs as $r){
if($f++) echo ',';
echo '["',$r['ccode'],'",
"',addslashes($r['city']),'",
"',$r['longitude'],'",
"',$r['latitude'],'"]';
}
echo ']}';
// }

In a nutshell, what happens is that the script counts how many cities are there in total, and then returns that count along with the first ten entries to the client browser using JSON as the transport.

Sign up for a Packt account to see the rest of this article

Now that you've read a few articles, you might want to consider signing up for a Packt account. It takes a matter of seconds, will give you access to all the articles on PacktPub.com, and once you've signed up you'll be returned here to carry on reading your article.

Furthermore, you'll gain access to nine free ebooks, and be offered a free trial of PacktLib, Packt's online library. Simply enter your details here, or log in to your existing account.

Log in

...or register

Thanks! by
So much easier to use with a step-by-step tutorial, rather than the documentation. Greeetings, George
Hi by
This is great! tried the documentation on datatables' site, but this is much easier to understand. To make this work with the latest version, change the name of this variable iSortDir_0 to -> sSortDir_0
show/hide hidden row information by
hi mr . kae I was pleasure reading and practicing and coding your explanation about DAtatables. only A person that knows mistakes that could occur in coding an example posibilytes an step by step example. thanks. now there is an example about show/hide information into a row. in server side processing item . he author is not clear in some cases and in API the example is not clear because adds some lines that there are not in initial one. I beg you to take a look at this article to send us a light to do a good code baout this important plugin. thanks again. carlos
thanks so much for the example by
Would it be possible to write a similar great explanation on adding Jeditable to DataTables? Thanks again, E
hi by
hi Thanks for the tutorial, but can you explain me more on the sort ? if i have only 2 fields then I will make $cols=array('idnota','tanggalnota'); actually I'm confused with this part: // { sort by $scol=0; if(isset($_REQUEST['iSortCol_0'])){ $scol=(int)$_REQUEST['iSortCol_0']; if($scol>3 || $scol<0) $scol=0; } $sdir='asc'; if(isset($_REQUEST['iSortDir_0'])){ if($_REQUEST['iSortDir_0']!='asc') $sdir='desc'; } $scol_name=$cols[$scol]; // } I still can't choose between asc and desc through the GUI. other works fine :) Thanks
problem running a example by
hi... i'm trying to run some your example and an get allways the same error: DataTables warning: JSON data from server failed to load or be parsed. This is most likely to be caused by a JSON formatting error. when i run the get_data i got the same result as you. But when i run the tables.html only shows the table structure without the data from the database. I've tried order example and got always the same result. thanks for your attention
Question regarding the table display by
Hi Kae, first of all I would liek to thank you for a great tutorial. I have a a question. I have been using your example but I have not been able to display the table. I was only able to display the table with no backgroud, css and nothing. it's justa table that is displayed. My jquery.min.js and datatables are in same directory but still nothing shows up. Want to know that do i need to get any flash player or anything like that in order to run this example. Please let me know as soon as possible. Thanks
Thanks! by
Thanks, this tutorial is great. I have one problem, however. I've copied your code over directly, I've only changed the database and directory info. Even though the iTotalRecords and iTotalDisplayRecords are passing the correct values (i've checked the JSON output), my table still just says "displaying 10 out of 10" at the bottom and disables the forward button. It's quite a mysterious problem, and totally disables AJAX pagination...
The same trick with ASP/SQL Server by
Hello Kae, Great coding, but could you give me a clue for the same trick in classic ASP en SQL Server? Or is that too far from home? Greetings, Robert
Thank you very much by
Thank you very much for this great tutorial. I've been trying to get a functional datatable for my website for almost a week now with just a few hopeful attempts till i finally reached your article. I appreciate how much detail you put into every single step explaining why we are putting every single line of code. So many tutorials around but this is the only one worked %100 for me.

Post new comment

Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Sort A-Z