0

this is related to my previous question about jqgrid. im doing now a search button that would search my inputed text from the server and display those data (if there is) in the jqgrid. Now, what i did is i create a global variable that stores the filters. Here's my javascript code for my searching and displaying:

    filter = ''; //this is my global variable for storing filters
    $('#btnsearchCode').click(function(){
       var row_data = '';
       var par = {
          "SessionID": $.cookie("ID"),
          "dataType": "data",
          "filters":[{
             "name":"code",
             "comparison":"starts_with",
             "value":$('#searchCode').val(),
          }],
          "recordLimit":50,
          "recordOffset":0,
          "rowDataAsObjects":false,
          "queryRowCount":true,
          "sort_descending_fields":"main_account_group_desc"
       }    
       filter="[{'name':'main_account_group_code','comparison':'starts_with','value':$('#searchCode').val()}]";
       $('#list1').setGridParam({
        url:'json.php?path=' + encodeURI('data/view') + '&json=' + encodeURI(JSON.stringify(par)), 
        datatype: Settings.ajaxDataType,  
       });
       $('#list1').trigger('reloadGrid');

       $.ajax({
           type: 'GET',
           url: 'json.php?' + $.param({path:'data/view',json:JSON.stringify(par)}),
           dataType: Settings.ajaxDataType,
           success: function(data) {
              if ('error' in data){
                 showMessage('ERROR: ' + data["error"]["msg"]);
              }
              else{                
                 if ( (JSON.stringify(data.result.main.row)) <= 0){
                     alert('code not found');
                 }
                 else{
                     var root=[];
                     $.each(data['result']['main']['rowdata'], function(rowIndex,  rowDataValue) {
                     var row = {};
                     $.each(rowDataValue, function(columnIndex, rowArrayValue) {
                        var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;        
                        row[fldName] = rowArrayValue;                   
                     });
                     root[rowIndex] = row;
                     row_data += JSON.stringify(root[rowIndex]) + '\r\n';
                });         
             }
             alert(row_data);  //this alerts all the data that starts with the inputed text...
          }
      }
    });
  }

i observed that the code always enter this (i am planning this code to use with my other tables) so i put the filter here:

   $.extend(jQuery.jgrid.defaults, {
       datatype: 'json',
       serializeGridData: function(postData) {
          var jsonParams = {
            'SessionID': $.cookie("ID"),    
            'dataType': 'data',
            'filters': filter,
            'recordLimit': postData.rows,
            'recordOffset': postData.rows * (postData.page - 1),
            'rowDataAsObjects': false,
            'queryRowCount': true,
            'sort_fields': postData.sidx
          };

          return 'json=' + JSON.stringify(jsonParams);
      },
      loadError: function(xhr, msg, e) { 
        showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
      },
    }); 

now, my question is, why is it that that it displayed an error message "Server Error: Parameter 'dataType' is not specified"? I already declared dataType in my code like above but it seems that its not reading it. Is there anybody here who can help me in this on how to show the searched data on the grid?(a function is a good help)

Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
jayAnn
  • 827
  • 3
  • 18
  • 38
  • It is important to know whether you use HTTP POST or GET for the server requests? In [one old answer](http://stackoverflow.com/questions/5374977/is-it-possible-to-include-an-event-in-a-javascript-function/5375479#5375479) I recommended you to use `postData` parameter of jqGrid. Do you use it? Could you include the current code of jqGrid which you use? You current `serializeGridData` implementation **ignore** many standard parameters of jqGrid and **ovewrite** it with yourth. Could you describe which parameters in which form you want to have on the server? – Oleg Apr 25 '11 at 09:24
  • It seems to me that there are exist an misunderstanding how jqGrid and `jQuery.ajax` build the URL used for the server requests (how `postData` will be used to append URL with additianal parameters). I could explain all exactly if it is needed. Could you exlain additionally why you need some strange **static** parameters `"dataType": "data"`, `"sort_fields":"main_account_group_desc"` and so on. What value has `Settings.ajaxDataType` and why the value is not static value 'json' or 'xml'? – Oleg Apr 25 '11 at 09:44
  • Oleg, please see my edit... i dont use postdata like the your previous answer. thats all the code i used. if i alert the row_data, it displays good answer. but the grid displays all data. i really can't explain what 'Settings.ajaxDataType' value has because me myself don't know. my senior only tells me to use it. – jayAnn Apr 26 '11 at 02:30
  • Could you include in the text of your question the code of jqGrid definition of `$('#list1')`? – Oleg Apr 29 '11 at 07:20
  • Oleg, i laready posted my jqGrid definition of $('#list1') in here: http://stackoverflow.com/questions/5814131/jqgrid-search-filter____. please see my edit. thanks – jayAnn Apr 29 '11 at 08:43

1 Answers1

1

I modified your code based on the information from both of your questions. As the result the code will be about the following:

var myGrid = $("#list1");

myGrid.jqGrid({
    datatype: 'local',
    url: 'json.php',
    postData: {
        path: 'data/view'
    },
    jsonReader: {
        root: function(obj) {
            var root = [], fields;

            if  (obj.hasOwnProperty('error')) {
                alert(obj.error['class'] + ' error: ' + obj.error.msg);
            } else {
                fields = obj.result.main.metadata.fields;
                $.each(obj.result.main.rowdata, function(rowIndex, rowDataValue) {
                    var row = {};
                    $.each(rowDataValue, function(columnIndex, rowArrayValue) {
                        row[fields[columnIndex].name] = rowArrayValue;
                    });
                    root.push(row);
                });
            }

            return root;
        },
        page: "result.main.page",
        total: "result.main.pageCount",
        records: "result.main.rows",
        repeatitems: false,
        id: "0"
    },
    serializeGridData: function(postData) {
        var filter = JSON.stringify([
            {
                name:'main_account_group_code',
                comparison:'starts_with',
                value:$('#searchCode').val()
            }
        ]);

        var jsonParams = {
            SessionID: $.cookie("ID"),
            dataType: 'data',
            filters: filter,
            recordLimit: postData.rows,
            recordOffset: postData.rows * (postData.page - 1),
            rowDataAsObjects: false,
            queryRowCount: true,
            sort_descending_fields:'main_account_group_desc',
            sort_fields: postData.sidx
        };

        return $.extend({},postData,{json:JSON.stringify(jsonParams)});
    },
    loadError: function(xhr, msg, e) {
        alert('HTTP error: ' + JSON.stringify(msg) + '.');
    },
    colNames:['Code', 'Description','Type'],
    colModel:[
        {name:'code'},
        {name:'desc'},
        {name:'type'}
    ],
    rowNum:10,
    viewrecords: true,
    rowList:[10,50,100],
    pager: '#tblDataPager1',
    sortname: 'desc',
    sortorder: 'desc',
    loadonce:false,
    height: 250,
    caption: "Main Account"
});
$("#btnsearchCode").click(function() {
    myGrid.setGridParam({datatype:'json',page:1}).trigger("reloadGrid");
});

You can see the code live here.

The code uses datatype:'local' at the beginning (at the 4th line), so you will have no requests to the server if the "Search" button is clicked. The serializeGridData the data from the postData parameter of serializeGridData will be combined with the postData parameter of jqGrid (the parameter "&path="+encodeURIComponent('data/view') will be appended). Additionally all standard jqGrid parameters will continue to be sent, and the new json parameter with your custom information will additionally be sent.

By the way, if you want rename some standard parameters used in the URL like the usage of recordLimit instead of rows you can use prmNames parameter in the form.

prmNames: { rows: "recordLimit" }
karel
  • 5,489
  • 46
  • 45
  • 50
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Hey Oleg, I've just tried your code... And yes, it is now working. Thanks a lot Oleg. Again, you help me. – jayAnn Apr 30 '11 at 05:28