JohnSmith
JohnSmith

Reputation: 1557

jqGrid: How to use single search feature?

How do I use the single search feature of jqGrid?

Im following the example "Single Search" under "New in version 3.7". jqGrid Demo Page

My script is almost exact save the queries used to retrieve data from the database but my script doesn't do the filtering.

Can anyone point me to a complete example of the single search feature using PHP?

I also have a question regarding the script in the demo page.

  1. How does jQuery pass the conditions to PHP to filter the results? I've notice in the query it had a variable $where but the variable wasn't declared in the PHP script.

Upvotes: 0

Views: 3020

Answers (1)

user1419445
user1419445

Reputation:

I've made up an example using the MySQL database.
First of all create a "test" database, an "items" table, and insert some records:

CREATE DATABASE IF NOT EXISTS test;

CREATE TABLE IF NOT EXISTS `items` (
  `item_id` int(11) NOT NULL,
  `item` varchar(255) DEFAULT '',
  `item_cd` varchar(255) DEFAULT '',
  PRIMARY KEY (`item_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

LOCK TABLES `items` WRITE;
INSERT INTO `items` VALUES (1,'Lorem','575878');
INSERT INTO `items` VALUES (2,'Lorem','857450');
INSERT INTO `items` VALUES (3,'ipsum','292404');
INSERT INTO `items` VALUES (4,'dolor','814131');
INSERT INTO `items` VALUES (5,'sit','962077');
INSERT INTO `items` VALUES (6,'amet,','549801');
INSERT INTO `items` VALUES (7,'sed','166822');
INSERT INTO `items` VALUES (8,'in','616758');
INSERT INTO `items` VALUES (9,'id','550799');
INSERT INTO `items` VALUES (10,'dictum','763004');
INSERT INTO `items` VALUES (11,'velit','244985');
INSERT INTO `items` VALUES (12,'est','525127');
INSERT INTO `items` VALUES (13,'suspendisse,','351690');
INSERT INTO `items` VALUES (14,'mauris','655061');
INSERT INTO `items` VALUES (15,'eget','423779');
INSERT INTO `items` VALUES (16,'imperdiet','493615');
INSERT INTO `items` VALUES (17,'ut,','864029');
INSERT INTO `items` VALUES (18,'mauris','546065');
INSERT INTO `items` VALUES (19,'vestibulum,','562819');
INSERT INTO `items` VALUES (20,'sagittis','238043');
INSERT INTO `items` VALUES (21,'ac.','867508');
INSERT INTO `items` VALUES (22,'Mauris','674897');
INSERT INTO `items` VALUES (23,'id','288097');
INSERT INTO `items` VALUES (24,'quam,','889530');
UNLOCK TABLES;

Next, create the html page "singlesearch.html":

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" media="screen" href="http://www.trirand.com/blog/jqgrid/themes/redmond/jquery-ui-custom.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="http://www.trirand.com/blog/jqgrid/themes/ui.jqgrid.css" />
    <script src="http://www.trirand.com/blog/jqgrid/js/jquery.js" type="text/javascript"></script>
    <script src="http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
    <script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.js" type="text/javascript"></script>
    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery("#single").jqGrid({
            url:'localset.php',
            datatype: "json",
            height: 255,
            width: 600,
            colNames:['Index','Name', 'Code'],
            colModel:[
                {name:'item_id',index:'item_id', width:65, sorttype:'int'},
                {name:'item'   ,index:'item'   , width:150},
                {name:'item_cd',index:'item_cd', width:100}
            ],
            rowNum:50,
            rowTotal: 2000,
            rowList : [20,30,50],
            loadonce: false,
            mtype: "GET",
            rownumbers: true,
            rownumWidth: 40,
            gridview: true,
            pager: '#psingle',
            sortname: 'item_id',
            viewrecords: true,
            sortorder: "asc",
            caption: "Single search on local data",
            loadError: function(jqXHR, textStatus, errorThrown) {
                /*
                alert('HTTP status code: ' + jqXHR.status + '\n' +
                      'textStatus: ' + textStatus + '\n' +
                      'errorThrown: ' + errorThrown);
                alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
                */
                alert(jqXHR.responseText);
            }
        });

        jQuery("#single").jqGrid(
            'navGrid',
            '#psingle',
            {del:false,add:false,edit:false},
            {},                        // default settings for edit
            {},                        // default settings for add
            {},                        // 
            {closeAfterSearch:true},   // search options
            {}                         // view parameters
        );
    });
    </script>
</head>
<body>
    <table id="single"></table>
    <div id="psingle"></div>
</body>
</html>

Then create a PHP page "localset.php":

<?php

function myTrace($str) {
    // Adjust the log file name before uncommenting
    //@file_put_contents("/tmp/localset.log", $str."\n", FILE_APPEND);
}

myTrace(print_r($_REQUEST,true));

// connect to the database
$link = mysqli_init();

// Adjust host, user, password and dbname before use!
$db = mysqli_real_connect($link, "myhost", "myuser", "mypass", "test");
if (!$db) {
    die('Connect Error ('.mysqli_connect_errno().'): '.mysqli_connect_error());
}

mysqli_set_charset($link, "utf8");

$page  = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;          // get the requested page
$limit = isset($_REQUEST['rows']) ? $_REQUEST['rows'] : 50;         // get how many rows we want to have into the grid
$sidx  = isset($_REQUEST['sidx']) ? $_REQUEST['sidx'] : 1;          // get index row - i.e. user click to sort
$sord  = isset($_REQUEST['sord']) ? $_REQUEST['sord'] : "asc";      // get the direction

if ($_REQUEST["_search"] == "false") {
    $where = "where 1";
} else {
    $operations = array(
        'eq' => "= '%s'",            // Equal
        'ne' => "<> '%s'",           // Not equal
        'lt' => "< '%s'",            // Less than
        'le' => "<= '%s'",           // Less than or equal
        'gt' => "> '%s'",            // Greater than
        'ge' => ">= '%s'",           // Greater or equal
        'bw' => "like '%s%%'",       // Begins With
        'bn' => "not like '%s%%'",   // Does not begin with
        'in' => "in ('%s')",         // In
        'ni' => "not in ('%s')",     // Not in
        'ew' => "like '%%%s'",       // Ends with
        'en' => "not like '%%%s'",   // Does not end with
        'cn' => "like '%%%s%%'",     // Contains
        'nc' => "not like '%%%s%%'", // Does not contain
        'nu' => "is null",           // Is null
        'nn' => "is not null"        // Is not null
    ); 
    $value = mysqli_real_escape_string($link, $_REQUEST["searchString"]);
    $where = sprintf("where %s ".$operations[$_REQUEST["searchOper"]], $_REQUEST["searchField"], $value);
}

$SQL = "SELECT item_id, item, item_cd FROM items ".$where." ORDER BY $sidx $sord";
myTrace($SQL);
$result = mysqli_query($link, $SQL);
if (!$result) {
    myTrace(mysqli_error($link));
    die("Couldn't execute query: ".mysqli_error($link));
}

if ($limit < 0) $limit = 0;

$start = ($limit * $page) - $limit;
if ($start < 0) $start = 0;

$count = mysqli_num_rows($result);
if ($count > 0) {
    $total_pages = ceil($count / $limit);
} else {
    $total_pages = 0;
}

if ($page > $total_pages) {
    $page = $total_pages;
}

$responce->page    = $page;
$responce->total   = $total_pages;
$responce->records = $count;

mysqli_data_seek($result, $start);
for ($i = 0; $row = mysqli_fetch_assoc($result); $i++) {
    if (($limit > 0) && ($i >= $limit)) break;
    $responce->rows[$i]['id']   = $row['item_id'];
    $responce->rows[$i]['cell'] = array($row['item_id'], $row['item'], $row['item_cd']);
} 
echo json_encode($responce);

mysqli_close($link);

?>

Enable the PHP mysqli extension in your PHP.INI file, adjust the connection parameters in the "localset.php" script (at line 15), and finally open the "singlesearch.html" page in your browser.

Upvotes: 3

Related Questions