Retrieve new dataset via select element

Retrieve new dataset via select element

RobRob Posts: 17Questions: 0Answers: 0
edited April 2009 in General
The following additions allow a select box (drop down box) to reload the data in a datatables instance. On the project I'm working on, I need to use a select box to change the data in the table (not just filter it). Choosing an option in the select box updates the where clause in the queries. Hopefully, someone finds this helpful. If there's a more efficient way to do this, let me know.


Add the fnReloadAjax plug-in to your code (http://datatables.net/plug-ins#api_fnReloadAjax).

Add a select box to your page:

[code]

Item 1
Item 2

[/code]

Add the following code to the "document ready" function:

[code]
/* Select box */
$('#select_box').change(function() {
// Reload data based on choice
oTable.fnReloadAjax();
})
[/code]

Add the following code to the datatables settings (as per http://datatables.net/1.5-beta/examples/server_side/custom_vars.html):

[code]
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( { "name": "where_select_box", "value": $("#select_box option:selected").val() } );
$.getJSON( sSource, aoData, function (json) {
fnCallback(json)
} );
}
[/code]

Within the server processing page, include the following code after the filtering (and individual column filtering) section:

[code]
/* Select Box Filtering */
if ( isset( $_GET['where_select_box'] ) )
{
$sWhere .= " AND item = '".mysql_real_escape_string($_GET['where_select_box'])."'";
}
[/code]

Add the following code after the "total query" sql statement (before $rResultTotal and $iTotal are executed):

[code]
/* Select Box Filtering */
if ( isset( $_GET['where_select_box'] ) )
{
$sQuery .= " AND item = '".mysql_real_escape_string($_GET['where_select_box'])."'";
}
[/code]

Note: I don't think I modified anything else within the server side processing page that would cause this not to work, but there's always a possibility.

Replies

  • allanallan Posts: 61,714Questions: 1Answers: 10,104 Site admin
    Hi Rob,

    That's awesome! Thanks very much for posting your example code :-)

    Allan
This discussion has been closed.