1

jqGrid Version: Guriddo jqGrid JS - v5.0.2

What is my Target ? I want to create a inline jqGrid. Here the Add will be done using a POST request, Edit will be done using a PUT request and delete will be done using a DELETE request.

What I have done so far ? I can do inline edit and delete using RESTful webService(by http PUT and DELETE request).

Here is the code -

var lastSel,
cancelEditing = function(myGrid) {
    var lrid;
    if (typeof lastSel !== "undefined") {
        myGrid.jqGrid('restoreRow', lastSel);
        lrid = $.jgrid.jqID(lastSel);
        $("tr#" + lrid + " div.ui-inline-edit, " + "tr#" + lrid + " div.ui-inline-del").show();
        $("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").hide();
    }
};
$.extend($.jgrid.defaults, {
ajaxRowOptions: {
    contentType: "application/json",
    async: true,type:"PUT",
    beforeSend: function(jqXHR, settings) {
        jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
        jqXHR.setRequestHeader("If-Match", '*');
    },
    complete: function(res, stat) {
        if (res.status == 200 || res.status == 204) {
            $("#jqGrid").trigger("reloadGrid");
        } else {
            return [false, res.responseText];
        }
    }
},
serializeRowData: function(data) {
    var propertyName, propertyValue, dataToSend = {};
    for (propertyName in data) {
        if (data.hasOwnProperty(propertyName)) {
            propertyValue = data[propertyName];
            if ($.isFunction(propertyValue)) {
                dataToSend[propertyName] = propertyValue();
            } else {
                dataToSend[propertyName] = propertyValue;
            }
        }
    }
    return JSON.stringify(dataToSend);
}
});

var thisGrid = $("#jqGrid").jqGrid({
datatype: "json",
url: 'https://localhost/MyWebService/academic/classroom/all',
editurl: 'https://localhost/MyWebService/academic/classroom',
loadBeforeSend: function(jqXHR) {
    jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
},
jsonReader: {
    repeatitems: false
},
colModel: [{
        label: 'Room Id',
        name: 'id',
        width: 10,
        hidden: true,
        key: true
    }, {
        label: 'Room Number',
        name: 'roomNo',
        editable: true,
        width: 100
    }, {
        label: "Edit Actions",
        name: "actions",
        width: 100,
        formatter: "actions",
        formatoptions: {
            keys: true,
            editOptions: {},
            addOptions: {
                mtype: 'POST'
            },
            delOptions: {
                mtype: 'DELETE',
                onclickSubmit: function(rp_ge) {
                    var selrow_id = thisGrid.getGridParam('selrow');
                    var rowdata = thisGrid.getRowData(selrow_id);
                    rp_ge.url = "https://localhost/MyWebService/academic/classroom" + '/' + selrow_id;
                },
                ajaxDelOptions: {
                    contentType: "application/json",
                    beforeSend: function(jqXHR) {
                        jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
                    }
                },
                serializeDelData: function(postdata) {
                    return JSON.stringify(postdata);
                }
            },
            onEdit: function(id) {
                if (typeof(lastSel) !== "undefined" && id !== lastSel) {
                    cancelEditing(thisGrid);
                }
                lastSel = id;
                $("#jqGrid").setGridParam({
                    editurl: "https://localhost/MyWebService/academic/classroom/" + encodeURIComponent(id)
                });
            }

        }
    }
],
sortname: 'id',
loadonce: true,
autowidth: true,
pager: "#jqGridPager",
rownumbers: true,
height: 500,

rowList: [], // disable page size dropdown
pgbuttons: false, // disable page control like next, back button
pgtext: null,

ondblClickRow: function(id, ri, ci, e) {
    if (typeof(lastSel) !== "undefined" && id !== lastSel) {
        cancelEditing($(this));
    }
    lastSel = id;
    var lrid = $.jgrid.jqID(lastSel);
    if (!e) e = window.event; // get browser independent object
    var element = e.target || e.srcElement;


    $("#jqGrid").jqGrid('editRow', id, true, function() {
        var colModel = jQuery("#jqGrid").jqGrid('getGridParam', 'colModel');
        var colName = colModel[ci].name;
        var input = $('#' + id + '_' + colName);
        console.log(input)
        setTimeout(function() {
            input.get(0).focus();
        }, 300);
    }, null, "https://localhost/MyWebService/academic/classroom/" + encodeURIComponent(id));
    $("tr#" + lrid + " div.ui-inline-edit, " + "tr#" + lrid + " div.ui-inline-del").hide();
    $("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").show();
}
});
var addOptions = {
keys: true,
type: "POST",
url: "https://localhost/MyWebService/academic/classroom/",
successfunc: function() {
    var $self = $(this);
    setTimeout(function() {
        $self.trigger("reloadGrid");
    }, 50);
    }
};
$("#jqGrid").jqGrid("inlineNav", "#jqGridPager", {
addParams: {
    position: "last",
    addRowParams: addOptions
    }
});

Problem : When I'm trying to save a newly created record I got the http request type PUT not POST. And I know the reason of it. Below code is responsible for that -

$.extend($.jgrid.defaults, {
    ajaxRowOptions: { contentType: "application/json", async: true,type:"PUT",

I can't override this type:"PUT" settings to type:"POST" during creating a new row.

There are some other cosmetic observation . I have provided that comment in the attached image file.

enter image description here

Edit 1 Here is my Updated Code :

  $.jgrid.defaults.responsive = true;
  $.jgrid.defaults.styleUI = 'Bootstrap';
  $.extend($.jgrid.inlineEdit, { restoreAfterError: false });

   var lastSel,
  cancelEditing = function(myGrid) {
    var lrid;
    if (typeof lastSel !== "undefined") {
      myGrid.jqGrid('restoreRow',lastSel);
      lrid = $.jgrid.jqID(lastSel);
      $("tr#" + lrid + " div.ui-inline-edit, " + "tr#" + lrid + " div.ui-inline-del").show();
      $("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").hide();
    }
  };
  $.extend($.jgrid.defaults, {
    ajaxRowOptions: { contentType: "application/json", async: true,
      beforeSend: function (jqXHR, settings) {
        jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
        jqXHR.setRequestHeader("If-Match", '*');
      },
      complete: function(res, stat) {
        if (res.status==200 || res.status==204) {
          $("#jqGrid").trigger("reloadGrid");
        } else {
          return [false, res.responseText ];
        }
      }
    },
    serializeRowData: function (data) {
      var propertyName, propertyValue, dataToSend = {};
      for (propertyName in data) {
        if (data.hasOwnProperty(propertyName)) {
          propertyValue = data[propertyName];
          if ($.isFunction(propertyValue)) {
            dataToSend[propertyName] = propertyValue();
          } else {
            dataToSend[propertyName] = propertyValue;
          }
        }
      }
      return JSON.stringify(dataToSend);
    }
  });

  var thisGrid =$("#jqGrid").jqGrid({
    datatype: "json",
    url: 'https://localhost/ums-webservice-common/academic/classroom/all',
    editurl:'https://localhost/ums-webservice-common/academic/classroom',
    loadBeforeSend: function(jqXHR) {
      jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
    },
    jsonReader: { repeatitems: false },
    colModel: [
      {
        label: 'Room Id',
        name: 'id',
        width: 10,
        hidden:true,
        key: true
      },
      {
        label: 'Room Number',
        name: 'roomNo',
        editable: true,
        width: 100
      },
      {
        label: 'Description',
        name: 'description',
        editable: true,
        width: 200
      },
      {
        label : 'Row',
        name: 'totalRow',
        width: 50,
        editable: true
      },
      {
        label: 'Column',
        name: 'totalColumn',
        width: 50,
        editable: true
      },
      {
        label: 'Capacity',
        name: 'capacity',
        width: 50,
        editable: true
      },
      {
        label: 'Room Type',
        name: 'roomType',
        editable: true,
        width: 100, align: 'center', formatter: 'select',
        edittype: 'select',
        editoptions: {
          value: '1:Theory;2:Sessional;0:Others',
          defaultValue: 'Theory'
        },
        stype: 'select',
        searchoptions: {
          sopt: ['eq', 'ne'],
          value: '1:Theory;2:Sessional;0:Others'
        }},


      {
        label: 'Dept./School',
        name: 'capacity',
        width: 100,
        editable: true
      },
      {
        label: 'Seat Plan',
        name: 'examSeatPlan',
        editable: true,
        width: 80, align: 'center', formatter: 'checkbox',
        edittype: 'checkbox', editoptions: {value: '1:0', defaultValue: '1'},
        stype: 'select',
        searchoptions: {
          sopt: ['eq', 'ne'],
          value: '1:Yes;0:No'
        }


      },
      {
        label: "Edit Actions",
        name: "actions",
        width: 100,
        formatter: "actions",
        formatoptions: {
          keys: true,
          editOptions: {
            mtype: 'PUT'
          },
          addOptions: {
            mtype: 'POST'
          },
          delOptions: {
            mtype: 'DELETE',
            onclickSubmit: function(rp_ge) {
              var selrow_id = thisGrid.getGridParam('selrow');
              var rowdata = thisGrid.getRowData(selrow_id);
              rp_ge.url = "https://localhost/ums-webservice-common/academic/classroom" + '/' + selrow_id ;
            },
            ajaxDelOptions: {
              contentType: "application/json",
              beforeSend: function(jqXHR) {
                jqXHR.setRequestHeader("Authorization", 'Basic ZHByZWdpc3RyYXI6MTIzNDU=');
              }
            },
            serializeDelData: function(postdata) {
              return JSON.stringify(postdata);
            }
          },
          onEdit: function (id) {
            if (typeof (lastSel) !== "undefined" && id !== lastSel) {
              cancelEditing(thisGrid);
            }
            lastSel = id;
            $("#jqGrid").setGridParam({ editurl: "https://localhost/ums-webservice-common/academic/classroom/" + encodeURIComponent(id)});
          }

        }
      }
    ],
    sortname: 'id',
    loadonce: true,
    autowidth: true,
    pager: "#jqGridPager",
    rownumbers: true,
    height:500,

    rowList: [],        // disable page size dropdown
    pgbuttons: false,     // disable page control like next, back button
    pgtext: null,

    ondblClickRow: function(id, ri, ci,e) {
      if (typeof (lastSel) !== "undefined" && id !== lastSel) {
        cancelEditing($(this));
      }
      lastSel = id;
      var lrid = $.jgrid.jqID(lastSel);
      if (!e) e = window.event; // get browser independent object
      var element = e.target || e.srcElement;


      $("#jqGrid").jqGrid('editRow',id,true,function() {
        var colModel = jQuery("#jqGrid").jqGrid ('getGridParam', 'colModel');
        var colName = colModel[ci].name;
        var input = $('#' + id + '_' + colName);
        console.log(input)
        setTimeout(function(){  input.get(0).focus(); }, 300);
      },null,"https://localhost/ums-webservice-common/academic/classroom/"+ encodeURIComponent(id));
      $("tr#" + lrid + " div.ui-inline-edit, " + "tr#" + lrid + " div.ui-inline-del").hide();
      $("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").show();
    }


    });


  var addOptions = {
    keys: true,
    mtype: "POST",
    url: "AddUser",
    successfunc: function () {
      var $self = $(this);
      setTimeout(function () {
        $self.trigger("reloadGrid");
      }, 50);
    }
  };
  $("#jqGrid").jqGrid("inlineNav", "#jqGridPager", {
    addParams: {
      position: "last",
      addRowParams: addOptions
    }
  });

}
ifti24
  • 191
  • 1
  • 5
  • 22

1 Answers1

1

Which version of jqGrid and from which fork of jqGrid (free jqGrid, Guriddo jqGrid JS or an old jqGrid in version <=4.7) you use? I develop free jqGrid fork and implemented some new features which simplify your requirements and additionally allows to simplify your code.

I'd recommend you to take a look in the answer. It shows how to use url and mtype as function in free jqGrid to make simple and clear read code for usage of RESTful services.

Alternatively you can hold your current code and the current jqGrid version which you use and just to remove type property from ajaxRowOptions. Instead of that you can use mtype parameter with "PUT" value only for Edit options and to use mtype: "POST" for Add options.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • I'm using Guriddo jqGrid JS - v5.0.2 . – ifti24 Feb 17 '16 at 01:19
  • What is your suggestion? Should I go with free jqGRid or Guriddo jqGrid? – ifti24 Feb 17 '16 at 08:42
  • @ifti24: I wrote you that I develop free jqGrid after changing the license agreement of jqGrid and renaming it to Guriddo jqGrid JS. It should be clear that I would recommend you to use my fork. You can test it just by changing URLs to URLs described in [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/Access-free-jqGrid-from-different-CDNs). If you still don't want or don't can upgrade jqGrid then you can follow the advice from the last paragraph of my answer (see starting with "Alternatively ...") – Oleg Feb 17 '16 at 08:49
  • I tried to remove `type` property from `ajaxRowOptions` and use mtype parameterws with `PUT` value for Edit options and `POST` for Add Options. The result is now the add with footer nav request is a `POST` request but the inline edit is now also `POST` instead of `PUT`. – ifti24 Feb 22 '16 at 10:27
  • **`mtype`**, not `mytype`. You should use `mtype: "PUT"` for editing. Which way you use now? `formatter: "actions"` or `inlineNav`? Which options exactly you use now? – Oleg Feb 22 '16 at 10:29
  • my mistake. I did tried with `mtype` but in the comment wrote wrongly. I'm trying with both the approach `formatter:"actions"` and `inlineNav`. I found a discussion which is closely related with my case - [Possibile bug in "mtype" option inside add/edit options](http://www.trirand.com/blog/?page_id=393/bugs/possibile-bug-in-mtype-option-inside-addedit-options) – ifti24 Feb 22 '16 at 10:45
  • @ifti24: The thread is very old and it's about `navGrid` and not about `inlineNav`. I see really no problems with the usage of REST services from jqGrid. Either you made some errors in your last tests or there are some Guriddo specific bug. I repeat that I develop alternative fork free jqGrid and I don't know specific Guriddo problems. You can append your question with **the current code**, which you use or just to try to change *temporary* URLs to jqGrid to free jqGrid 4.13.0 described [here](https://github.com/free-jqgrid/jqGrid/wiki/Access-free-jqGrid-from-different-CDNs). – Oleg Feb 22 '16 at 10:54
  • I have added my latest code in the **Edit 1 Section** . Please check `editOptions` and `addOPtions` under `formatoptions` for `formatter:"actions"` – ifti24 Feb 22 '16 at 11:04
  • 1
    @ifti24: `formatoptions.addOptions` are wrong. The options don't exist at all (no "Add" button exist), but you should specify `mtype: "PUT"` inside of `formatoptions`. The call of `editRow` inside of `ondblClickRow` is wrong too, because it will use `mtype: "POST"` instead of `"PUT"`. The options of `inlineNav` are wrong too: you don't specified `editParams` with `"PUT"`. By the way, you can have funny effects if you start editing with double-click or `formatter: "actions"` and then press `"Save"` button on inline Nav. I fixed some bugs in the case in free jqGrid and all work syncronously. – Oleg Feb 22 '16 at 11:17
  • Thanks for your continuous support. I'm accepting your answer. Your last comment helped me to fix the problem in my code and now it is working perfectly. I have another question how can i do client and server side validation for inline edit/add. But I will surely create a new ticket for that. – ifti24 Feb 23 '16 at 06:10