1

When there is a jqGrid on the page I want to extend it to pass an extra parameter in. My best attempt so far:

...
    $('[role=grid]').jqGrid('setGridParam', { 'serializeGridData':MyGridOnBeforeRequest });

    function MyGridOnBeforeRequest (postData) {
        var newPostData = $.extend(postData, {
            specialParam: "foo"
        });
        return $.param(newPostData);
    }
...

I am doing it this way because it looks like jqGrid ignores any changes you do to jQuery's ajax handling.

Thanks.

Kev
  • 2,656
  • 3
  • 39
  • 63

2 Answers2

4

In general the code which you posted should work and at the next grid reloading the new serializeGridData will be used.

It's only a little strange that you use serializeGridData in the way in which you as posted. It's enough to use postData parameter instead:

var postData = $('#grid').jqGrid('getGridParam', "postData");
$.extend(postData: {specialParam: "foo"});

Moreover in your original code you use $.extend(postData, {specialParam: "foo"}); which modify the original postData. It's not bad, but in general the code

function myGridOnBeforeRequest (postData) {
    return $.extend({}, postData, {specialParam: "foo"});
}

or even

function myGridOnBeforeRequest (postData) {
    return $.extend(true, {}, postData, {specialParam: "foo"});
}

will be more clean. The usage of $.param is not really needed. If you return an object then jQuery.ajax will make the call of $.param automatically for you.

One more very common way will be to define grids directly with the postData parameter which looks like

postData: {
    specialParam: function () { return "foo"; }
}

In the way you can implement more logic in the function, you can use some variables from the outer scote inside of the body of the function or get some values from the controls existing on the page (see here for details). In the case you can implement dynamic specialParam without the usage of getGridParam.

The last remark. Already from the color of myGridOnBeforeRequest (compare it with the color of MyGridOnBeforeRequest from your question) one can see that it will be interpreted in another way. If the name of the function start with the capital letter it means correspond with common used name conversion that you define constructor of the new class MyGridOnBeforeRequest. You have to use it as var test = new MyGridOnBeforeRequest();: using new. Just compare with var now = new Date();. It is strictly recommended to hold the standard JavaScript name conversion.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
1

If it is going to be some setting that is not going to change much you can add it to the $.jgrid.defaults by using something like this

function getSpecialParam()
{
    return 'foo';
}
$.jgrid.defaults = $.extend($.jgrid.defaults,
    {
        postedData:{
            specialParam:getSpeicalParam
        }
    });
Qpirate
  • 2,078
  • 1
  • 29
  • 41