Search code examples
javascriptphpjqueryjsgrid

Loading js-grid then filtering data


I have data being pulled from a db using php and then passed into javascript to load js-grid. I also have a dropdown populated with php containing the default value selected and stored by the user. My goal is to populate the grid with all data returned, then filter it based on the selected option in the dropdown.

I can't seem to understand how to load then filter data using js-grid.

<script type="text/javascript">var order_json = <?= $order_json ?>; var user_list = <?= $user_list['activeListId'] ?>;</script>
<script type="text/javascript" src="js/main.js"></script>

main.js

$( document ).ready(function() {
$("#jsGrid").jsGrid({
    width: "100%",
    height: "400px",

    inserting: false,
    editing: false,
    sorting: true,
    paging: false,
    pageSize: 30,

    noDataContent: "No orders found",

    data: order_json,

    fields: [
        { name: "OrderId", type: "number", title: "Order ID", visible: false },
        { name: "ListId", type: "number", title: "Order List ID", visible: true},
        { name: "Name", type: "text", title: "Order Name", align: "left"}
    ],
});
var grid = $("#jsGrid").data("JSGrid");
  grid.search({ListId: user_list})
});

I have tried some different approaches and none have worked. Any help would be appreciated.


Solution

  • With js-grid the actual filtering of the data should be implemented by developer. The filtering could be done on the client-side or server-side. Client-side filtering implemented in loadData method of controller. Server-side filtering is done by a server script that receives filtering parameters, and uses them to retrieve data.

    Here is how your controller.loadData method could look like:

    loadData: function(filter) {
        var d = $.Deferred();
    
        // server-side filtering
        $.ajax({
            type: "GET",
            url: "/items",
            data: filter,
            dataType: "json"
        }).done(function(result) {
            // client-side filtering
            result = $.grep(result, function(item) {
                 return item.SomeField === filter.SomeField;
            });
    
            d.resolve(result);
        })
    
        return d.promise();
    }
    

    As for data option, it's used only for static grid data.

    Worth to mention that it would be better to provide data to grid with a REST-y service (of course, it can be done with PHP). Here is the sample project showing how to use js-grid with a REST service on PHP https://github.com/tabalinas/jsgrid-php.