My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
TutorialPropertiesAndDocumentation  
Nearly-complete list of all the parameters available from Flexigrid.
Featured
Updated May 2, 2011 by eric.caron

Tutorial

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 http://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() {
	$("#flex1").flexigrid({
		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
	});
});

Properties

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:

<?php
// Connect to MySQL database
mysql_connect('server', 'username', 'password');
mysql_select_db('dbname');
$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
$searchSql";
$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
$searchSql
$sortSql
$limitSql";
$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.

Buttons

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.

Tutorial originally assembled by the talented folks at http://www.kenthouse.com/

Comment by stan...@gmail.com, May 18, 2011

thanks for your sharing

Comment by charlesc...@gmail.com, May 27, 2011

Thank you so much, this plug in help me a lot :)

Comment by qq3285...@gmail.com, Jun 1, 2011

Thank you, this plug in help me a lot too

Comment by youyouk....@gmail.com, Jun 2, 2011

Very nice and usefull datagrid. thank you for your help and your hard work made on Flexigrid :)

Comment by rg.edg...@gmail.com, Jun 7, 2011

Gracias esta excelente...

Comment by rcwb...@gmail.com, Jun 8, 2011

Can you give an exact example of what the JSON string looks like? I've tried duplicating this with my data, but the grid just will not populate any rows. I can't see a good way to debug it. It is seeing my number of rows, though, in the pager at the bottom, so it is in fact hitting my json_send.php. So I'm pretty sure that my JSON string doesn't look exactly like it should. Are all of the element names required exactly as shown here? (page, total, cell)

Now, the example above doesn't pass the field names in, which doesn't seem right to me, but I tried it both ways. The first way:

{	"page":1,
	"total":3,
	"rows":[
			{
				"id":1,
				"cell":[1,"06\/03\/2011","123","abc1"]
			},
			{
				"id":2,
				"cell":[2,"06\/03\/2011","124","abc2"]
			},
			{
				"id":3,
				"cell":[3,"06\/04\/2011","125","abc3"]
			}
			]
}

So I assume that would just assign the fields to the columns in the colDef in the order received. But since I'd like for it to use the field names to assign to the column names of the same name :) here's the other way I tried:

{
	"page": 1,
	"total": 3,
	"rows": [{
		"id": 1,
		"cell": {
			"id": 1,
			"date": "06\/03\/2011",
			"account_number": "123",
			"name": "abc1"
		}
	}, {
		"id": 2,
		"cell": {
			"id": 2,
			"date": "06\/03\/2011",
			"account_number": "124",
			"name": "abc2"
		}
	}, {
		"id": 3,
		"cell": {
			"id": 3,
			"date": "06\/04\/2011",
			"account_number": "125",
			"name": "abc3"
		}
	}]
}
Comment by rcwb...@gmail.com, Jun 8, 2011

I figured it out. IE8 was in Quirks mode. Doh!

Comment by catont...@gmail.com, Jun 12, 2011

Great... A comprehensive tutorial. I'm going to try it out. Thanks for posting this!!

Comment by h_kon...@yahoo.com, Jun 15, 2011

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...Can you help me to Add and edit row in line?

Comment by h_kon...@yahoo.com, Jun 15, 2011

Parameters display,width,sortable,align,hide,serchable I put in comments...

<?php

$contents="";
$fields=""; $sortname=""; $searchfilter=""; foreach($array_tables[$tablename]1? AS $key => $value) {
if($sortname=="")
$sortname=$key;
$parts=explode(",", $value);
$display=$parts0?; $width=$parts1?; $sortable=$parts2?; $align=$parts3?; $hide=$parts4?; $search=$parts5?;

if($search=='true') {
if($searchfilter=='') $searchDefault=', isdefault: true'; else $searchDefault=''; $searchfilter.="{display: '".$display."', name: '".$key.$searchDefault."'},";
}

$contents.="{display: '$display', name : '".$key."', width : $width, sortable : $sortable, align: '$align', hide: $hide},"; $fields.=$key.",";
} $contents=substr($contents,0,-1); $fields=substr($fields,0,-1); $searchfilter=rtrim($searchfilter,","); echo $contents."\n";
/ ?>

Comment by AMarqui...@gmail.com, Jun 17, 2011

Muchas gracias por el aporte del grid, muchas gracias!!!!!!

Comment by AMarqui...@gmail.com, Jun 17, 2011

Thank you very much for the contribution of the grid, thank you very much !!!!!!

Comment by ekirul...@gmail.com, Jun 19, 2011

how do i get the select page number (page) and result per page (rp) javascript code?

Comment by yangxian...@gmail.com, Jun 20, 2011

非常感谢!!!

Comment by xiaoxian...@163.com, Jun 27, 2011

Great! I like it very much! The grid is very beautiful! Thank you very much!

Comment by abbeya...@gmail.com, Jul 1, 2011

You seem to be missing all the properties for the colmodel:

name (this is the database field name used for ajax calls) width height sortable: true/false align: left/center/right hide: true/false searchable: true/false (only applicable if you have the search bar turned on)

Comment by laurent....@gmail.com, Jul 6, 2011

How we can disable colomn sort? Thx!

Comment by xxyba...@gmail.com, Jul 8, 2011

顶楼主!

Comment by umair...@gmail.com, Jul 12, 2011

Can anyone help me on how to serialize data from web service and how should it look like after serialization ?

Comment by ricardomontesrodriguez, Jul 20, 2011

Como seria la utilizacion con postgresql?

Comment by 30.vinod...@gmail.com, Aug 5, 2011

How can I bind row with event, actually I wanted to call some other js funcion on clicking a row.

Comment by joel.ol...@gmail.com, Aug 5, 2011

Thanks in advance for the plugin. I have included my code below. Grid is empty though the result set does have data. I can't seem to spot my error. The bottom bar of the grid displays "Displaying 1 to null of null items":

<script language="javascript"> $(function() { $("#req").flexigrid( { url: 'getRequests.php', dataType: 'json',

colModel : [ {display: 'Form No', name : 'formno', width : 60, sortable : true, align: 'left'}, {display: 'School', name : 'school', width : 50, sortable : true, align: 'left'}, {display: 'Organization', name : 'org', width : 90, sortable : true, align: 'left'}, {display: 'Sponsor', name : 'sponsor', width : 58, sortable : true, align: 'left'}, {display: 'Start Date', name : 'start_dte', width : 72, sortable : true, align: 'left'}, {display: 'End Date', name : 'end_dte', width : 65, sortable : true, align: 'left'}, {display: 'Activity', name : 'activity', width : 52, sortable : true, align: 'left'}, {display: 'Date Req', name : 'dated', width : 66, sortable : true, align: 'left'}, {display: 'Approved', name : 'approved', width : 67, sortable : true, align: 'left'}, {display: 'Reconciled', name : 'reconciled', width : 76, sortable : true, align: 'left'} ], / buttons : [ {name: 'Edit', bclass: 'edit', onpress : doCommand}, {name: 'Delete', bclass: 'delete', onpress : doCommand}, {separator: true} ], / searchitems : [ {display: 'Form Number', name : 'formno'}, {display: 'School', name : 'school', isdefault: true}, {display: 'End Date', name : 'end_dte'} ], sortname: "formno", sortorder: "desc", usepager: true, title: "Fundraiser Requests", useRp: true, rp: 10, showTableToggleBtn: false, resizable: true, width: 900, height: 370, singleSelect: true } ); }); </script> <div id="req"></div>

getRequests script:

mysql_connect( $server, $dbuser, $dbpass ); mysql_select_db( 'fundRaiser' );

// initial parameters until user input is sent $page = 1; $rp = 10; $sortname = "formno"; $sortorder = 'desc'; $qtype = ''; // Search column $query = ''; // Search string

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 request $searchSql"; $result = mysql_query($sql); $Crow = mysql_fetch_array($result); $total = $Crow0?;

// 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 formno, school, org, sponsor, start_dte, end_dte, activity, dated, approved, reconciled from request $searchSql $sortSql $limitSql"; $results = mysql_query($sql); while ($row = mysql_fetch_assoc($results)) { $data['rows'] = array( 'id' => $row['formno'], 'cell' => array($row['formno'], $row['school'], $row['org'], $row['sponsor'], $row['start_dte'], $row['end_dte'], $row['activity'], $row['dated'], $row['approved'],$row['reconciled'] ) ); } echo json_encode($data);

flexigird.js param is: dataType: 'json'

echo json:

{"page":1,"total":"13","rows":[{"id":"1331312507220","cell":["1331312507220","133","Wills Staff","Rogers, Ronda A.","1312347600","1317358800","t-shirt sales","1312507356","x","n"]},{"id":"0491312488879","cell":["0491312488879","049","6th grade P.E.","Jones, Mindy D","1312347600","1313730000","P.E. Uniforms","1312489006","x","n"]},{"id":"0491312488719","cell":["0491312488719","049","Girls Athletics","Jones, Mindy D","1313643600","1314939600","Waterbottles for games","1312488874","x","n"]},{"id":"0491312475858","cell":["0491312475858","049","LdZ Creative Publications","Denniston, Shannon R","1312347600","1338526800","yearbook sales","1312476326","y","n"]},{"id":"0461312563009","cell":["0461312563009","046","Band","Baker, Terry B.","1314594000","1315544400","cookie dough","1312563334","x","n"]},{"id":"0451312479894","cell":["0451312479894","045","Band","Pecht, Suzanne R","1314939600","1316149200","catalogue brochure","1312480080","y","n"]},{"id":"0441312561791","cell":["0441312561791","044","Choir","Brooks, Kathryn E","1314853200","1315890000","Brochure Sales","1312562073","y","n"]},{"id":"0041312484577","cell":["0041312484577","004","Student Council","Jones, Lisa D.","1313470800","1330495200","Volleyball & Basketball Concession Stands","1312484662","x","n"]},{"id":"0041312484447","cell":["0041312484447","004","Student Council","Jones, Lisa D.","1321250400","1323410400","Beef Jerky","1312484543","x","n"]},{"id":"0041312484236","cell":["0041312484236","004","Student Council","Jones, Lisa D.","1313989200","1320991200","Silicone Wristbands","1312484411","x","n"]}]}

Comment by joel.ol...@gmail.com, Aug 8, 2011

Oh - never mind, Json support might need to be enable ... :-\

Comment by alexandr...@gmail.com, Aug 10, 2011

How can I reinitialize the table from an outside event? For example, I want when a button is pressed to refresh the table. I'm using the JSON server request.

Thanks

Comment by TerryZe...@gmail.com, Aug 11, 2011

我也顶

Comment by jorge.ca...@gmail.com, Aug 24, 2011

esto no sirve.... ya lo he puesto de mil maneras.... y colocado una mini tabla... y nada de esto funciona... muy buena.. pero .. tienen que dejar de hacer perder el tiempo a la gente... con funciones infuncionales...

Comment by yashmang...@gmail.com, Aug 24, 2011

Hi,

Thanks for sharing. Just want to find out how can I use this in Classic ASP to return the data from database. Sorry I am not into PHP.

Comment by talktopi...@gmail.com, Aug 28, 2011

@alexandr...@gmail.com, if you create wrapper div, use JS to create the table and append it to the wrapper div $("#wrapper_div").html(''); //Assuming html is created <div id="wrapper_div"></div> var list_table = $('<table />'); //Create the table dynamically $("#wrapper_div").append(summary_list_table); //Append the table to the wrapper DIV

$(list_table).flexigrid({ .......

Hope that helps.

Comment by aguilhe...@gmail.com, Sep 1, 2011

Hello, Eric, I liked your tutorial I decided to do a translation into Portuguese (Brazil) and post on my blog. Visit me and rate (http://telecomatica.blogspot.com/2011/09/tutorial-flexigrid.html) Hugs and thanks for sharing knowledge.

Comment by v.dam...@gmail.com, Sep 15, 2011

Hello Eric,

I'm using flexgrid and is really cool. Actually I only can't understand how enable horizontal scrolling. Could you please help me please?

You can see what I'm doing here:

http://wp.damore.it/wp-content/myfacebookbattle/fqltester.html

Best regards, Vincenzo

Comment by *s...@e-magination.co.za, Sep 18, 2011

I am using flexigrid it works great. I need to display info based on an ID that I retrieve.

I am passing the ID in the url. Which can be retrieved using $GET["id"] in the php file that ouputs to json format. My issue comes with specifying the url in the javascript. As the Grid shows processing data (it is obviously not pointing to the right url).

What would be the best way of displaying records based on parameters passed from a previous page?

Thanks in advance, I hope you understand what I am asking.

Regards,

Seán

Comment by d.sathis...@gmail.com, Sep 23, 2011

Is that possible to set colModel property from json data dynamically?

Comment by varga.ba...@prometheusportal.hu, Sep 26, 2011

Hy, I suggest following modification: Line 757

btnDiv.innerHTML = "<div><span>" + (typeof(btn.display) != 'undefined' ? btn.display : btn.name) + "</span></div>";

This is most helpful for multi-language development.

By, Balázs

Comment by mesta...@gmail.com, Oct 7, 2011

Hi, Thanks for Flexigrid, it works fine.

How do I re-initialize the flexigrid on a page without reloading the page?

I have loaded the flexigrid with data, but in response to an event, I want to clear the rid and load new data into the grid.

It seems flexigrid ignores the second function call to load data.

Comment by ectech...@gmail.com, Oct 11, 2011

Does anyone have a working example of the delete portion of this script? I cannot seem to get this working and I am somewhat new to jquery/json data. Whenever I try to delete a record it comes back with an error message: "Query: undefined - Total affected rows: undefined". I know I should post some code but i'm not sure what part I need to post on here.. Please help!

Comment by bleut...@gmail.com, Oct 13, 2011

Hi, thx for this plugin, it's very useful but can you add callback function ?

Comment by bertrand...@gmail.com, Oct 18, 2011

Is it possible to use Flexigrid with jquerytools ?

Comment by h...@software-partner-solutions.com, Oct 30, 2011

The flexigrid is absolut a great control and it works really fine! But i have one question. Is it possible when i click in a row to become the value of 2 fields seclected by fieldname(column name) ? My colmodel by example:

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'}],

My wish is simply, when i click the row, my result is Position and Surname. Thank you for your trouble.

Chears from Hamburg (germany) Heike

hs@software-partner-solutions.com

Comment by longsho...@gmail.com, Oct 30, 2011

Hello, is it possible to save the position of the columns? And identify those that are hidden by default?

Comment by GabiL...@gmail.com, Nov 10, 2011

Hello, I have another question how can one, on server-side treat posted data with multiple instances of this flexigrid control ?

Thanks, I haven't read all the posts but i did a quick search and didn't found the topic.

Comment by c.kif....@gmail.com, Nov 15, 2011

hello great work thank you how to use it with jquery 1.7 ?? i use 1.7 version to user other parts of my page which don't work with jquery 1.2.3

Comment by shirk...@gmail.com, Nov 21, 2011

A mi no me carga nada. Lo ejecuto pero no ejecuta la función flexigrid, y la estoy incluyendo correctamente porque en el script flexigrid.js si que entra, pero en lo que es la función flexigrid no. Qué puede pasar?

Comment by kang...@gmail.com, Nov 21, 2011

how to show sort number (on the most left column) instead of ID ?

Comment by prasad.l...@gmail.com, Nov 22, 2011

im having trouble using this flexigrid plug-in.

can anyoby help me here.

here is my code:

client-code:

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script src="js/flexigrid.js"></script> <script type="text/javascript">

$(function() {
$("#result").flexigrid({
url: 'uesr-list.php', dataType: 'json', colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'left'}, {display: 'OAuth_Provider', name : 'oauth_provider', width : 150, sortable : true, align: 'left' {display: 'Email ID', name : 'email', width : 150, sortable : true, align: 'left'}, {display: 'User Name', name : 'username', width : 250, sortable : true, align: 'left'},
{display: 'Joined', name : 'createdtime', width : 250, sortable : true, align: 'left'}, {display: 'Last Active', name : 'lastmodified', 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 : 'firstname'}, {display: 'Last Name', name : 'lastname', isdefault: true}, {display: 'Username', name : 'username'}
], sortname: "id", sortorder: "asc", usepager: true, title: "Users", useRp: true, rp: 10, showTableToggleBtn: false, resizable: false, width: 700, height: 370, singleSelect: true
});
}); </script> </head> <body> Loading Users Data <table id="result"> </table> </body> </html>

Server-side script:

<?php // Connect to MySQL database mysql_connect('localhost', 'root', 'indavest'); mysql_select_db('disagreeme'); $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 $searchSql"; $result = mysql_query($sql); $row = mysql_fetch_array($result); $total = $row0?; // 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(); /ORIGINAL SQL QUERY/ $sql = "select id, oauth_provider, email, username, createdtime, lastmodified from usermember $searchSql $sortSql $limitSql"; $results = mysql_query($sql); while ($row = mysql_fetch_assoc($results)) { $data['rows'] = array( 'id' => $row['id'], 'cell' => array($row['id'], $row['oauth_provider'], $row['email'], $row['username'], $row['createdtime'], $row['lastmodified'], ) ); } echo json_encode($data); ?>

my database structure:

+----------------+--------------+------+-----+---------------------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------------------+-------+ | id | varchar(50) | NO | PRI | NULL | | | oauth_provider | varchar(255) | YES | | NULL | | | oauth_uid | varchar(255) | YES | | NULL | | | email | varchar(255) | YES | | NULL | | | username | varchar(255) | NO | | NULL | | | createdTime | timestamp | NO | | 0000-00-00 00:00:00 | | | lastModified | timestamp | NO | | CURRENT_TIMESTAMP | | | password | varchar(255) | YES | | NULL | | +----------------+--------------+------+-----+---------------------+-------+

Thanks in advance

Comment by fro...@gmail.com, Nov 24, 2011

I'm having some troubles to make my columns sortable, i can't seem to use the colModel property, do i need to add anything to the table html to be able to use the colModel or it just works when you have AJAX interaction?

Comment by yangxian...@gmail.com, Nov 28, 2011

I come again and thanks again. I found a little INCOMPATIBLE PROBLEM. When I used the "Flexigrid for jQuery - v1.1" in asp.net mvc 2.0 which brought jQuery 1.4.1 by vs 2010, it was ok. But When I used it in asp.net mvc 3.0 which brought jQuery 1.4.4, it was blocked with ERROR on line 703. I researched the code, and modify the line 703.

the original line is: if ($(cm).attr('hide')) {

I modified to: if (cm.hide) {

I test that it was well both in the jQuery 1.4.1 and 1.4.4. I hope you can review what I modified, after all you understand your code more precisely. thank you for providing such excellent tool.

Comment by jeremychuahy@gmail.com, Dec 1, 2011

Hi thanks for this great plugin. However i wanted to update the table using push. Using Event Source of HTML 5.

I wonder if its possible to do it with flexi with a pinch of a salt.! Cheers!

Comment by Filipe...@gmail.com, Dec 18, 2011

Great stuff, congrats! I used the examples in this page, along with the "buttons" function, however the table get's it's objects the fields get the data, but the "Edit" and "delete" button don't work.

When i select a "row" and click a button (edit or delete) i get an error: Uncaught TypeError?: Cannot call method 'lastIndexOf' of undefined

I'm using JQuery v1.7.1.

anyone else has this error? is there a fix?

Again, thanks for the "flexigrid" stuff, very nice ;)

Comment by surbhi.0...@gmail.com, Dec 19, 2011

Hiiii, can you please help me out with "how" to change the date and time format in flexigrid?"

Comment by simon1...@gmail.com, Dec 19, 2011

Could somebody provide an example of how to delete data from the grid? I know how to delete data from the db but I don't see any function to remove data from the grid. Do I have to reload the grid?

Comment by simon1...@gmail.com, Dec 21, 2011

nevermind, it's .remove(). We need more documentation.

Comment by slash...@gmail.com, Dec 21, 2011

Can flexigrid implement with mongoDB? mongoDB use json for document.

Comment by manusinh...@gmail.com, Jan 4, 2012

Can anyone suggest how to access the page nos(once i change it from 1 to 2 or 3) in js where am displaying the data or in jsp where I have included the js.

Comment by u...@4-tell.com, Jan 31, 2012

I have seen this question but nowhere the answer: I want to reload the data in my flexigrid after one of the parameters changes. How do I do this?

Comment by liu.norm...@gmail.com, Feb 6, 2012

great datagrid really.... thx for the grid.

Comment by diginova...@gmail.com, Feb 11, 2012

Thanks for the grid. It all came together very easily, which was great. However, and I know this question was asked before, but what is the best way to call some other js funcion on clicking/selecting a row? Thank you.

Comment by vijaysai...@gmail.com, Feb 14, 2012

Hello Dear

please give me the simplest way to implement this code into php.
please sir give me demo file so that i will implement it to my code. i tried many time but i faced many problem .so it's humble request from my side to give demostation of code. Thanking you Vijay Saini

Comment by m...@allflags.com.br, Feb 25, 2012

Pegando o Id ao clicar no linha //Picking up the Id by clicking on the line

$("#flex1").click(function() {

var id; $('.trSelected').each(function() {
id = $(this).attr('id'); id = id.substring(id.lastIndexOf('row')+3);
});
});

Comment by anderson...@gmail.com, Mar 5, 2012

Buenos dias, solo con agregar estas tres ultimas lineas a la funcion addRowProp en el flexigrid.pack.js, podran obtener el id solo con seleccionar la fila, sin necesidad de presionar ningun boton.

addRowProp : function() {

$('tbody tr', g.bDiv).each(function() {
$(this).click(function(e) {
var obj = (e.target || e.srcElement);
if (obj.href || obj.type)
return true;
$(this).toggleClass('trSelected'); if (p.singleSelect)
$(this).siblings().removeClass('trSelected')
var id = $(this).attr('id');
id = id.substring(id.lastIndexOf('row')+3);
//funcion(id);
alert("Ha seleccionado la id: " + id);

Comment by dlgn...@gmail.com, Mar 21, 2012

Hi there~

I wanna remove select button on header.

example...

I have 5 columns but I don't wanna column show/hide button on 1st header.

How can I do?

please help me~

Comment by jroberto...@gmail.com, Mar 22, 2012

Hi therre

my code don´t works, can you help me? :P

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Flexigrid</title> <link rel="stylesheet" type="text/css" href="flexigrid/css/flexigrid.css"> <script type="text/javascript" src="jq/development-bundle/jquery-1.7.1.js"></script> <script type="text/javascript" src="/flexigrid/js/flexigrid.js"></script> </head>

<body> <table id="flex1" style="display:none"></table>

<script type="text/javascript">

$(function() {

$("#flex1").flexigrid({
url: 'post2.php', dataType: 'json', colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'left'} {display: 'Engine', name : 'engine', width : 40, sortable : true, align: 'left'}, {display: 'Browser', name : 'browser', width : 150, sortable : true, align: 'left'}, {display: 'Plataform', name : 'plataform', width : 150, sortable : true, align: 'left'}, {display: 'Version', name : 'version', width : 250, sortable : true, align: 'left'}, {display: 'Grade', name : 'grade', width : 250, sortable : true, align: 'left'}
], buttons : [
{name: 'Edit', bclass: 'edit', onpress : doCommand}, {name: 'Delete', bclass: 'delete', onpress : doCommand}, {separator: true}
], searchitems : [
{display: 'Browser', name : 'browser'} //{display: 'Surname', name : 'surname', isdefault: true}, //{display: 'Position', name : 'position'}
], sortname: "id", sortorder: "asc", usepager: true, title: "Operative System", useRp: true, rp: 10, showTableToggleBtn: false, resizable: false, width: 700, height: 370, singleSelect: true
});
})

</script>

</body>

</html>

Comment by imran.tu...@gmail.com, Mar 22, 2012

To disable show/hide option on a particular column... here is what I did:

update 1?

... if (p.colModel) { //create model if any
thead = document.createElement('thead'); var tr = document.createElement('tr'); for (var i = 0; i < p.colModel.length; i++) {
var cm = p.colModeli?; var th = document.createElement('th'); th.innerHTML = cm.display; if (cm.name && cm.sortable) {
$(th).attr('abbr', cm.name);
} // ADDED: check and add nohide attribute to header if (cm.nohide) {
$(th).attr('nohide', true);
} else {
$(th).attr('nohide', false);
}
...

update 2?

$('th div', g.hDiv).each(function () {
var kcol = $("th[axis='col" + cn + "']", g.hDiv)0?; var chk = 'checked="checked"'; if (kcol.style.display == 'none') {
chk = '';
} // ADDED: check no hide/show column flag if ($(this.parentElement).attr("nohide") != "true") {
$('tbody', g.nDiv).append('<tr><td class="ndcol1"><input type="checkbox" ' + chk + ' class="togCol" value="' + cn + '" /></td><td class="ndcol2">' + this.innerHTML + '</td></tr>');
} cn++;
});

And in your html, where you call flexigrid(...) update the colModel input parameter, and pass nohide attribute ...

e.g.

colModel : [ {
display : '', name : 'si', width : 24, sortable : false, align : 'center', nohide: true
}, {
display : 'ID', name : 'id', width : 64, sortable : true, align : 'left'
}, {
Comment by Mateusz....@gmail.com, Apr 5, 2012

If somebody would to get preprocessed data from row you have to use $(".class tbody tr").live only this worked for me

Comment by jana.jam...@gmail.com, Apr 18, 2012

Olá estou precisando de ajuda preciso dar um change

searchitems : [ {
display : 'Data de Atividade', name : 'dbo.fn_dateformat(B.AtivamData?,1) AS DataAtividade?', isdefault : true
}, {
display : 'Período', name : 'DesTurno?'

}

no periodo, póis ao clicar nele tenho q exibir dos inputs

Comment by dhharri...@gmail.com, May 23 (3 days ago)

Does anybody know if an event is passed back when the user adjusts the height of the table?


Sign in to add a comment
Powered by Google Project Hosting