Flexigrid Tutorial

20 July 2009 by Andrew Irvine  
Filed under News and views

Here at Kent House we are always looking at new ways to improve the user experience of our sites. I have recently been creating an application for a client and found an excellent jQuery-based component which will give your site the look and feel of a more traditional application if you are having to navigate between large sets of database records.

This is the Flexigrid written by Paulo P. Marinas. There isn’t a lot of documentation around for this jQuery plugin so I decided to create this tutorial which might be of benefit to someone.


As you can see the component is very intuitive and includes features to:

  • Search for records matching your supplied criteria (by first clicking the search icon).
  • Sort in either ascending or descending order by a selected column.
  • Hide and show columns to make optimum use of available space.
  • Navigate between pages using the navigation icons or jump straight to a particular page.

How to Use

Adding the Flexigrid to your webpage couldn’t be easier. Just download the code from www.flexigrid.info and copy the required files into your site’s directories. You must also have a version of jQuery running on your site for this to work which can be found at jquery.com.

You will find a flexigrid.js file in the downloaded archive. Include this file in the head section of your site as you would normally do along with the provided CSS file (you will need to copy across the entire contents of the ‘css’ directory including the images).

After creating a table element on your page with an id of ‘flex1′ for this example you can then create and include a javascript file consisting of the following code. The Flexigrid will then be created on page load.

$(function() {
url: 'staff.php',
dataType: 'json',
colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'left'},
{display: 'First Name', name : 'first_name', width : 150, sortable : true, align: 'left'},
{display: 'Surname', name : 'surname', width : 150, sortable : true, align: 'left'},
{display: 'Position', name : 'email', width : 250, sortable : true, align: 'left'}
buttons : [
{name: 'Edit', bclass: 'edit', onpress : doCommand},
{name: 'Delete', bclass: 'delete', onpress : doCommand},
{separator: true}
searchitems : [
{display: 'First Name', name : 'first_name'},
{display: 'Surname', name : 'surname', isdefault: true},
{display: 'Position', name : 'position'}
sortname: "id",
sortorder: "asc",
usepager: true,
title: "Staff",
useRp: true,
rp: 10,
showTableToggleBtn: false,
resizable: false,
width: 700,
height: 370,
singleSelect: true


Using the above as a basis for your grid, you can customise it to suit your requirements using several javascript properties. For example, you can specify on which column the results should be sorted initially and whether to sort in ascending or descending order. The most common properties are shown below.

Property Description
url This is a URL of the server-side script which provides a JSON or XML representation of the results to display in the grid using AJAX.
dataType You can choose to have your server-side script return either JSON or XML data.
colModel This is an array containing a list of columns to use. You can set the display name, the width, whether the column can be sorted, and text alignment.
buttons It is possible using this array to add buttons along the top of the Flexigrid specifying a callback function, e.g. you may want to create buttons to add, edit, and delete records. The bClass property is the CSS class used to set the background image for the button, etc.
searchItems Using this you can specify which columns to use for searching the results using the ‘quick search’ area. You simply specify a display name for the search option, the column name, and whether the column is the default search option.
sortname This property is used to specify the initial column to sort on.
sortorder Specifying either ‘asc’ or ‘desc’ for this property will set the initial sort order.
usepager The page navigation buttons can be turned on or off using this property.
title This is the title which will appear at the top of the Flexigrid.
useRp Whether to allow the user to specify the number of results per page.
rp The initial number of results per page.
showTableToggleBtn This will enable/disable minimisation of the Flexigrid with an icon in the top right corner.
width The width of the Flexigrid.
height The height of the Flexigrid.
singleSelect This undocumented property is used to indicate that only one row can be selected at a time. This is useful if you would like to create buttons such as edit or delete which apply only to a single row.

The Server-side Script

For this example I will be using a PHP script to return the JSON results filtered by the criteria specified within the Flexigrid.

The following data is posted to our script using AJAX and can be found in PHP’s $_POST array.

Parameter Description
page Current page number.
sortname The name of the column to sort by.
sortorder The order to sort by – ‘asc’ or ‘desc’.
qtype The column selected during ‘quick search’.
query The text used within a search.
rp The number of records to be returned.

Now that we have this information we can go ahead and create the script.

// Connect to MySQL database
mysql_connect('server', 'username', 'password');
$page = 1; // The current page
$sortname = 'id'; // Sort column
$sortorder = 'asc'; // Sort order
$qtype = ''; // Search column
$query = ''; // Search string
// Get posted data
if (isset($_POST['page'])) {
$page = mysql_real_escape_string($_POST['page']);
if (isset($_POST['sortname'])) {
$sortname = mysql_real_escape_string($_POST['sortname']);
if (isset($_POST['sortorder'])) {
$sortorder = mysql_real_escape_string($_POST['sortorder']);
if (isset($_POST['qtype'])) {
$qtype = mysql_real_escape_string($_POST['qtype']);
if (isset($_POST['query'])) {
$query = mysql_real_escape_string($_POST['query']);
if (isset($_POST['rp'])) {
$rp = mysql_real_escape_string($_POST['rp']);
// Setup sort and search SQL using posted data
$sortSql = "order by $sortname $sortorder";
$searchSql = ($qtype != '' && $query != '') ? "where $qtype = '$query'" : '';
// Get total count of records
$sql = "select count(*)
from staff
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];
// Setup paging SQL
$pageStart = ($page-1)*$rp;
$limitSql = "limit $pageStart, $rp";
// Return JSON data
$data = array();
$data['page'] = $page;
$data['total'] = $total;
$data['rows'] = array();
$sql = "select id, first_name, surname, position
from staff
$results = mysql_query($sql);
while ($row = mysql_fetch_assoc($results)) {
$data['rows'][] = array(
'id' => $row['id'],
'cell' => array($row['id'], $row['first_name'], $row['surname'], $row['position'])
echo json_encode($data);

There’s nothing too complicated here. We simply connect to a MySQL database (substitute the connection variables for the values corresponding to your own database), create the SQL from the data supplied by Flexigrid, get the number of records in the entire result set and return the results in JSON format using the json_encode function which is available to PHP versions 5.2.0 and later.

Flexigrid requires a few parameters to be passed back in the JSON array. These are:

Parameter Description
page The current page number.
total The total number of records in the result set. Used by Flexigrid to calculate the number of pages.
rows This is an array containing the data for the rows. Each row needs a unique id (used within the id for the HTML ‘tr’ element) and an array of column data.


In the javascript listing above we specified that the doCommand function should be called when either the ‘edit’ or ‘delete’ buttons are clicked on. How does Flexigrid know which button has been clicked on? Two parameters are passed to the function. These are the name of the command which in this case can be either ‘Edit’ or ‘Delete’, and the grid object.

All we are concerned with doing in this tutorial is finding an id for the selected row. When we have this we can easily perform whatever operation we wish on the data for the selected record using e.g. AJAX techniques which are beyond the scope of this tutorial.

function doCommand(com, grid) {
if (com == 'Edit') {
$('.trSelected', grid).each(function() {
var id = $(this).attr('id');
id = id.substring(id.lastIndexOf('row')+3);
alert("Edit row " + id);
} else if (com == 'Delete') {
$('.trSelected', grid).each(function() {
var id = $(this).attr('id');
id = id.substring(id.lastIndexOf('row')+3);
alert("Delete row " + id);

As you can see it is just a case of finding the selected row using jQuery. We then extract the numeric id of the record from the id of the HTML ‘tr’ element. You are free from this point on to implement the editing and adding functions however you’d like e.g. using jQuery UI dialogs.


This tutorial has looked into the use of the freely available Flexigrid plugin for jQuery. We have found documentation to be lacking but hopefully this tutorial has gone some way to helping people understand this handy extension. If you’d like to find out more I recommend that you take a look at the source code (flexigrid.js).

If you find Flexigrid useful I suggest you make a small donation to the creator to help maintain the project at www.flexigrid.info.


92 Responses to “Flexigrid Tutorial”
  1. Nice tutorial, Andrew.

  2. brume says:

    Flexigrid looks like a very promising jquery datagrid plugin. I have some questions about it.

    1. Unfortunately, it doesnt seem like the Flexigrid project is still undergoing active development/maintenance. Aren’t you concerned about this?.

    2. Did you consider other jquery data grids before selecting the flexigrid?. If so what were the considerations?.

    I am considering a number of jquery data grid options and wanted to hear your opinion….

    please get back.


  3. Hi. I chose Flexigrid as it is a lightweight jQuery-based datagrid. I looked into the jqGrid (plugins.jquery.com/project/jqGrids) but found that it did a lot more than what I wanted it to do (e.g. inline editing) and was a bit bulky.

    Although the main Flexigrid site (www.flexigrid.info) isn’t kept updated, there is still an active community at http://groups.google.com/group/flexigrid who occasionally contribute updates.

  4. Tony O'Hara says:

    Hi guys, I am trying to use Flexigrid in a web application. Some of my screens have scrollable divs and I am finding that Flexigrid does not display correctly on these pages. It spills over from its ‘parent’ control and doesn’t move with the rest of the page. This doesn’t seem to be a problem in IE8 or Firefox but it is with IE6 & 7. Any ideas?

    thanks in advance


  5. ssalter says:

    Good to see a tutorial with the json encoding that php5 offers.

    You might want to change:
    while ($row = mysql_fetch_assoc($sql)) {
    while ($row = mysql_fetch_assoc($results)) {
    in your example above.

    Additionally, how about providing a zip for users to download, complete with a sql file so they can load a test table. Anything to make it easier for the user, right?

    How to detect a row onclick event and pass the ID of the row to a defined javascript function?

    How to reload the grid and pass different sql?

    How to turn off pagination entirely so the entire result is displayed in the grid?

    :) Questions, questions.


  6. ssalter says:

    cancel #4 and $5.

  7. Kevin Holdridge says:

    Hi Steve – thanks for spotting that blooper – we’ve corrected the sample now. Andrew will see what he can do with items 2 and 3 when he gets back from vacation – useful suggestions. Kevin

  8. indra says:

    Nice, Easy & Usesfull. This is tutorial that I need

  9. Ganesh Prasad says:

    Is is possible to implement a “Edit” link in the grid row itself instead of “Edit” button in the main menu so that one click extra click can be avoided by the user?
    Please let me know if any body can help me on this.

  10. indra says:

    This tutorial very usefull,but how if I want to adding input form for searching(maybe)?
    ex: I want search the data between startdate and enddate?

  11. rmw says:


    I wanted to add a feature where i added a column Option buttons, which i managed to do, but now i want to add another feature to Select & Unselect all records displayed in the grid.

    Could anyone help me on this ASAP.

  12. Damian Stafford says:

    Thank you very much for the clearest explanation I’ve encountered so far for this useful yet almost completely undocumented library.

  13. Ramiro says:

    Hi there !!

    I’m working with this Flexigrid (very nice) and I have a question about it.
    How Can I get the column value (!=’id’) of the selected row?
    e.g. My Felxigrid has 4 columns, but I need get the value of the column 2.
    Thanks for yuo help.

  14. ayesha says:

    plz upload sample zip file

  15. ayesha says:

    you can get id by simple table tr or td click function using jquery.

  16. Ashish says:

    Is it possible to make add section like when we click on it than the present screen which is currently showing the content, just slide down and a new screen appears with an “add new entry form” and same with edit???

  17. Ashish says:

    If this is possible than please mail me

  18. bani says:

    Hide and show columns is also possible, but when i try to hide a column the page which is below is getting disturbed, the column names are moving but the actual columns are there..its like deleting the column id disturbing the way the page looks…is it possible to delete the entire row not just the name of the column…..so that the table stays stable

  19. bertopola says:

    First of all sorry for my english if I make mistakes. I’ll go direct to the question:

    How to do multi-column sort in Flexigrid? Posible?


  20. Saneef says:

    Any idea if the flexigrid like colspan & rowspan in HTML tables?

  21. david says:

    very good tutorial

  22. One more question ….. ? is there any way by virtue of which i can create a edit or delete button per row and then when clicked on that row it will delete that particular row only

  23. Yanike says:

    Also, how can you make a column of data have links?

    One user found a way here -> http://stackoverflow.com/questions/931944/flexigrid-adding-a-column-with-links

    But his coding is different from yours. Please help us out with linking data :)

  24. Yanike says:

    Also, is there a way to make the search better. Right now, it only finds things verbatim. I need what it to be able to find anything containing the search text.

    Like if I search “can”, I want it to find “candle, rescan, pecan, 1-can-0, etc..” instead of just find “can”.

  25. Marc Borgers says:

    Thanks for tutorial !

    There is a OnSuccess property in which a callback can be supplied that is called whan the load is succesfull.

  26. Ranjith Siji says:

    Great Tutorial. I Used Flexigrid with CodeIgniter in my projects. It is very helpful for creating admin pages. In place Editing is a great feature to be added. Also the External Form Control is also useful. I followed. http://flexigrid.eyeviewdesign.com/. And made some changes in My HTML Code and achieved the editing part.

  27. Hai, can anyone help me?
    I want to get the value from selected row in flexigrid and throw it to other function, but i dont know how :(

  28. Peter Reich says:

    To get the rowdata pass the obj from clickedcell-subfunction and you will get the dataArray.

    The names in the array are only available from colums which are sortable!!!

    Hope it helps

    // für alle Grids verwendbar
    function RowData (obj) {
    var myArray = new Array();

    // get row and col of clicked item
    if (obj.innerHTML != undefined) {
    var colIndex = $(obj).closest(’tr’).children().index($(obj).closest(’td’));
    myArray['col'] = colIndex;

    var rowIndex = $(obj).closest(’tbody’).children().index($(obj).closest(’tr’));
    myArray['row'] = rowIndex;

    if (obj.innerHTML != undefined) {
    myArray['clickedfieldnr'] = colIndex;
    myArray['clickedfieldname'] = $(obj).closest(’.flexigrid’).find(’.hDivBox’).find(’thead’).find(’th’)[colIndex].abbr; myArray['clickedfieldvalue'] = obj.innerHTML.trim();

    id = $(obj).closest(’tr’).attr(’id’);
    id = id.substr(3);
    myArray['rowid'] = id;

    var erg = ‘Row:\”+rowIndex+’\’ /Col:\”+colIndex+’\'\n’;
    erg = erg + ‘RowID:\”+id+’\'\n\n’;

    erg = erg + ‘clickedfieldnr: \”+myArray['clickedfieldnr'] + ‘\’\n’;
    erg = erg + ‘clickedfieldname: \”+myArray['clickedfieldname'] + ‘\’\n’;
    erg = erg + ‘clickedfieldvalue: \”+myArray['clickedfieldvalue'] + ‘\’\n’;

    erg = erg + ‘\nFields:\n’;

    var row = $(obj).closest(’tr’); // actual row
    var tdarr = $(row).find(’td’);
    var colcount = 0;
    function () {
    inhalt = $(this).text().trim();
    abbrev = $(obj).closest(’.flexigrid’).find(’.hDivBox’).find(’thead’).find(’th’)[colcount].abbr; // jetzt geht es
    abbrev = abbrev.trim();
    erg = erg + abbrev + ‘=\” + inhalt + ‘\’\n’;
    colcount = colcount + 1;
    // alert(abbrev+’='+inhalt);
    myArray[abbrev] = inhalt;
    myArray['erg'] = erg;
    // alert (erg);
    return myArray;

  29. Hey Andrew, in your properties table you wrote “searchItems” while the correct name is “searchitems”, with lowercase i.

    Regards and thanks for the tutorial, very useful ;)

  30. prepaid says:


    i am very interest in this flexigrid stuff, but i have questions, is it possible to put pictures and links in the rows ?

    and maybe someone has a example ?

  31. kiran says:

    Hi You can add links and images in rows as below

    $json .= “cell:['".$db->record['ID'].”‘,’”.$db->record['Name'].”‘,’”.addslashes($db->record['State']).”‘,’”.addslashes($db->record['Phone']).”‘]”;
    $json .= “}”;

  32. kiran says:

    i mean to say like this in json

    $json .= “cell:['<a id=".record['ID'].”>”.$db->record['ID'].”</a>’]”;

  33. Pierre says:

    Just an adaptation with ADODB and particularly with oracle DB. The LIMIT X, Y is not existing on oracle you might modifiy or extends it for particularry use in line 151 :
    $this->SQL = ‘SELECT * from (’.($this->SQL).’) where rownum > ‘.$start. ‘ and rownum rp).’ ‘.$sort; Here is code.

    // FIRST CLASS EXTENDS FlexiGrid Class

    // MAIN CLASS .
    setDSN($DSN); }
    if(!is_null($SQL)) { $this->setSQL($SQL); }
    $this->typedsn = $type;
    if(count($pkey)>0) {
    $this->key = $pkey;
    public function setKeys($keys) {
    $this->key = $keys;
    public function Out() {
    $this->data = $this->runSql();
    $buf = $this->GetDataXml($this->page,$this->numberrows,$this->data,$this->key);
    return $buf;
    public function setSQL($sql) {
    $this->SQL = $sql;
    public function getSQL() {
    return $this->SQL ;
    public function setDSN($dsn) {

    $this->DSN = $dsn;
    $db = &ADONewConnection($this->DSN);

    if (!$db) die(”Connection failed”);

    $this->db = $db;

    return $db;

    public function runSQL($sql=null) {

    if(is_null($sql)) {
    $sql = $this->SQL;

    $resultdata = $this->db->GetArray($sql);
    return $resultdata;
    public function countRec() {
    $sql_ = “SELECT count(*) AS NUM_ROWS FROM (”.$this->SQL.”)”;
    $datas = $this->runSQL($sql_);
    foreach ($datas as $data) {
    $this->numberrows = $data['NUM_ROWS'];
    return $this->numberrows;
    public function getDSN() {
    return $this->DSN ;
    public function headerAjaxFlexigrid() {
    header(”Expires: Mon, 26 Jul 1997 05:00:00 GMT” );
    header(”Last-Modified: ” . gmdate( “D, d M Y H:i:s” ) . “GMT” );
    header(”Cache-Control: no-cache, must-revalidate” );
    header(”Pragma: no-cache” );
    header(”Content-type: text/json”);

    public function GetDataXml($page=0,$total=0,$data,$key) {
    $json = “”;
    $json .= “{\n”;
    $json .= “page: $page,\n”;
    $json .= “total: $total,\n”;
    $json .= “rows: [";

    $myidkey = implode(',',$key);

    $rc = false;
    while ($row = array_pop($data)) {
    if ($rc) $json .= ",";
    $json .= "\n{";
    $json .= "id:'".$row[$myidkey].”‘,”;
    $json .= “cell:[";

    $nb = count($row)/2; // car on a index de type 0, ID, 1 NAME, 2 TOTO etc.. etc...
    foreach($row as $key_=>$row_) {

    if(is_string($key_)) {
    $json .= "'".addslashes(utf8_encode(trim($row_)))."'";
    if($ijson = $json;
    return $this->json;
    public function getArrayKeys($array) {
    $array_keys = array_keys($array);
    foreach($array_keys as $array_key) {
    if(is_string($array_key)) {
    $keys[$array_key] = $array_key;
    return $keys;
    public function prepareFlexigrid($page_=null,$rp_=null, $sortname_=null,$sortorder_=null) {
    $this->page = !is_null($page_) ? $page_ : $_POST['page'];
    $this->rp = !is_null($rp_) ? $rp_ : $_POST['rp'];
    $this->sortname = !is_null($sortname_) ? $sortname_ : $_POST['sortname'];
    $this->sortorder = !is_null($sortorder_) ? $sortorder_ : $_POST['sortorder'];
    if (!$this->sortname) $this->sortname = ‘rownum’;
    if (!$this->sortorder) $this->sortorder = ‘desc’;
    $sort = “ORDER BY $this->sortname $this->sortorder”;
    if (!$this->page) $this->page = 1;
    if (!$this->rp) $this->rp = 10;
    $start = (($this->page-1) * $this->rp);
    $this->SQL = ‘SELECT * from (’.($this->SQL).’) where rownum > ‘.$start. ‘ and rownum rp).’ ‘.$sort;
    $result = $this->runSQL();
    $this->numberrows = $this->countRec();

  34. hakeem says:

    hi all,

    very good tutorial really thanks to author great job but a help needed

    i want to retrieve column names from db dynamically plus number of columns also, because i can have different columns names and number

    waiting for urgent reply pls

  35. waheed says:

    hi i have a problem i m using jquery datepicker to select dates range to search data that will be populated in flexigrid but somehow it is conflicting with flexigrid any solution for it ??

    these are the files which i m using

  36. Bob says:

    There is another undocumented property that may be of use. You can also include the property “params” to pass other parameters in the Ajax call. For example:

    params: [
    {name: 'edbName' , value:'parm1Value'}

  37. Pedro Augusto Vidal says:

    Tnxs for this tutorial! It’s helpe me, and much!

    Great tutorial, but have errors in json…

  38. Rahul says:

    Hello ,

    Thanks a lot for this tutorial.
    I have one question regarding this flex grid is that can we add a checkbox column to this grd ??
    Please let me know ASAP will be really heplful.
    Thanks a lot in advanced

  39. Ajith says:

    How do i generate dynamic columns. At present it seems to me only Pre-declared columns that we declare?? Please help!

    my id is ajithkamathk@gmail.com

    Please PLease do revert back cos its very urgent and i am running hell short of time!

  40. Pepo says:

    Pierre can you give me your mail, i have a question for you


  41. dms says:

    how would we display both a grid and the details in a form? For example as scrolling via the grid a form below would display the details.

    This way if a grid has 20+ columns they would be able to view all the fields in the form.

    Even better we could make the form editable for updates

    I believe the relationship is commonly known as grid to detail form. as you select different row_ids the form display the respected data.

    let me know if this can be accomplished, as I haven’t been able to find any documentation on this.

  42. rg says:

    I am using flexigrid to show my data to the users. I am refreshing the data every 2 seconds using flexaddData
    But in Internet Explorer I am running into memory issues. I have used tools to check where the memory leaks are happening. It teams that the table rows created by flexigrid are not removed and hang in the memory when we call flexadddata the second time around.
    Has anyone faced such issue and knows how to clear the data from flexigrid. This will be quite helpful

  43. Kevin Holdridge says:

    Hello everyone. Andrew Irvine posted this tutorial back in the summer of 2009, and it has certainly proved very popular. Unfortunately, Andrew moved on to new pastures a while ago and, as he was our FlexiGrid guru, there’s now nobody at Kent House in a position to provide guidance and support on this application. We are. of course, happy to leave the thread up and to encourage colleagues out in the community to post queries and answers. But, if you need more urgent help you might be better trying in the Google Groups page for this product at:

  44. kathiresan says:

    Very Nice Tutorial Andrew Irvine ……….

  45. sivakathir says:

    Need 1 Help Please …..
    How to fix search the data between startdate and enddate in Flexi Grid ????….

  46. Karthick says:

    hi all

    I finished Flexigrid using php jquey json but flexigrid jquery source files does not support jquery dialog box how to overcome this please help me give a sample code

  47. Michael says:

    Hi All

    Would anyone be able to tell me how to reload the results after I have deleted a entry.

    function test(com, grid) {
    if (com == ‘Inbox’) {

    } else if (com == ‘Reply’) {
    $(’.trSelected’, grid).each(function() {
    var id = $(this).attr(’id’);
    id = id.substring(id.lastIndexOf(’row’)+3);
    MailAction(”REPLY”, id)
    } else if (com == ‘Delete’) {
    $(’.trSelected’, grid).each(function() {
    var id = $(this).attr(’id’);
    id = id.substring(id.lastIndexOf(’row’)+3);
    MailAction(”DELETE”, id)

    Thank you

  48. Kontos Harry says:

    I edit index and post file. Now I can load, search and delete anything table from my database who having comments in table and fields dynamic…Can you help me to Add and edit row?

  49. Navid Kianfar says:

    @Michael :
    try : $(’#grid’).flexReload();



Check out what others are saying about this post...
  1. [...] Grazie per le indicazioni bumm. Ho risolto il problema applicando le indicazioni che ho trovato su QUESTO TUTORIAL modificando il mio codice in questo modo: [...]

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!