|
TutorialPropertiesAndDocumentation
Nearly-complete list of all the parameters available from Flexigrid.
Featured Tutorial
As you can see the component is very intuitive and includes features to:
How to UseAdding 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
});
});PropertiesUsing 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.
The Server-side ScriptFor 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: 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:
ButtonsIn 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/ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
thanks for your sharing
Thank you so much, this plug in help me a lot :)
Thank you, this plug in help me a lot too
Very nice and usefull datagrid. thank you for your help and your hard work made on Flexigrid :)
Gracias esta excelente...
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" } }] }I figured it out. IE8 was in Quirks mode. Doh!
Great... A comprehensive tutorial. I'm going to try it out. Thanks for posting this!!
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?
Parameters display,width,sortable,align,hide,serchable I put in comments...
<?php
}
/ ?>Muchas gracias por el aporte del grid, muchas gracias!!!!!!
Thank you very much for the contribution of the grid, thank you very much !!!!!!
how do i get the select page number (page) and result per page (rp) javascript code?
非常感谢!!!
Great! I like it very much! The grid is very beautiful! Thank you very much!
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)
How we can disable colomn sort? Thx!
顶楼主!
Can anyone help me on how to serialize data from web service and how should it look like after serialization ?
Como seria la utilizacion con postgresql?
How can I bind row with event, actually I wanted to call some other js funcion on clicking a row.
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"]}]}
Oh - never mind, Json support might need to be enable ... :-\
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
我也顶
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...
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.
@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.
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.
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
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
Is that possible to set colModel property from json data dynamically?
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
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.
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!
Hi, thx for this plugin, it's very useful but can you add callback function ?
Is it possible to use Flexigrid with jquerytools ?
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 : [
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
Hello, is it possible to save the position of the columns? And identify those that are hidden by default?
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.
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
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?
how to show sort number (on the most left column) instead of ID ?
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">
}); </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'])) { POST['page']); } if (isset($POST['sortname'])) { POST['sortname']); } if (isset($POST['sortorder'])) { POST['sortorder']); } if (isset($POST['qtype'])) { POST['qtype']); } if (isset($POST['query'])) { POST['query']); } if (isset($POST['rp'])) { 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
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?
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.
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!
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 ;)
Hiiii, can you please help me out with "how" to change the date and time format in flexigrid?"
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?
nevermind, it's .remove(). We need more documentation.
Can flexigrid implement with mongoDB? mongoDB use json for document.
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.
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?
great datagrid really.... thx for the grid.
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.
Hello Dear
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 SainiPegando o Id ao clicar no linha //Picking up the Id by clicking on the line
$("#flex1").click(function() {
});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() {
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~
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() {
})</script>
</body>
</html>
To disable show/hide option on a particular column... here is what I did:
update 1?
update 2?
And in your html, where you call flexigrid(...) update the colModel input parameter, and pass nohide attribute ...
e.g.
If somebody would to get preprocessed data from row you have to use $(".class tbody tr").live only this worked for me
Olá estou precisando de ajuda preciso dar um change
no periodo, póis ao clicar nele tenho q exibir dos inputs
Does anybody know if an event is passed back when the user adjusts the height of the table?