0

I try to make server - client connection, using Java Restful, JqGRID and SQL Server. I have a problem with my jqGrid. In my grid I have 9 columns, but when I execute, the grid return:

{"firstname": "Jojo ","surname":"Bobo","chefdepartment":"No","position":" Position 3","joinyear":"09/17/2015","oper":"add","id":"jqg1"}

whithout the values for username, email and experience, and in my database (SQL server) will return:

values('"Jojo "' , '"Bobo"' , 'null' , 'null' , '"No"' , '" Position 3"' , '"09/17/2015"' , 'null')

, so return "null" for username, email and experience.

I use getCell, for take the values like this:

    firstname = grid.jqGrid('getCell', Id, "firstname");
                surname = grid.jqGrid('getCell', Id, "surname");
                username = grid.jqGrid('getCell', Id, "username");
                username = firstname + "." + surname;
                email = username + "@test.com";

jqGRID code:

grid.jqGrid({

    data: mydata,
    mtype:'GET',
    datatype:'json',
    url:'http://localhost:8080/JDBCapplication/app/test/get',
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8'},
    serializeGridData: function (postdata) {

        return JSON.stringify(postdata);
        },
        jsonReader : {
            root:"rows",
            page: "page",
            total: "total",
            records: "records",
            cell: "",
            repeatitems: false,
         },


    autowidth: true,
    height: 200,
    editurl:'http://localhost:8080/JDBCapplication/app/test/post',
    gridview: true,
    colModel: [ 
        {name: 'id', label: 'Id', width: 150, align: 'center', search:false},  
        {name: 'firstname', label: 'Firstname', align:'center', editable: true, searchoptions:{sopt:['eq','ne','bw','ew','cn','nc']}, editoptions: {defaultValue: ' '},formatter: 'text'}, 
        {name: 'surname', label: 'Surname', align:'center', editable: true, searchoptions:{sopt:['eq','ne','bw','ew','cn','nc']}, editoptions: {defaultValue: ' '},formatter: 'text'}, 

        {name: 'username', label: 'Username', align:'center', searchoptions:{sopt:['eq','ne','bw','ew','cn','nc']}},
        {name: 'email', label: 'Email', align:'center', searchoptions:{sopt:['eq','ne','bw','ew','cn','nc']}},
        {name: 'chefdepartment', label: 'Chef Department', editable: true, align: 'center',
        edittype: "checkbox",  formatter: chefdepFunc, editoptions:{ dataEvents: checkboxEdit, value: "Yes:No", defaultValue: 'No'}, 
        stype:'select', searchoptions:{value: "Yes:Yes; No:No",sopt:['eq','ne']}
        }, 
        {name: 'position', label: 'Position', editable: true, align: 'center',
        edittype: "select", formatter: 'select', editoptions:{value: ' : ; Position 1:Position 1; Position 2:Position 2; Position 3:Position 3; Position 4:Position 4; Position 5:Position 5'},
        stype: 'select', searchoptions:{value: ' : ; Position 1:Position 1; Position 2:Position 2; Position 3:Position 3; Position 4:Position 4; Position 5:Position 5', sopt:['eq','ne']}

        },

        {name: 'joinyear', label : 'Join Year', align: 'center', editable: true, editoptions: { size: 20, maxlengh: 10,
            dataInit: function(e) 
                     { $(e).datepicker({ dateFormat: 'mm/dd/yy' });
                     } },
            searchtype:'datepicker', searchoptions:{size: 20, maxlengh: 10,
            dataInit: function(e) 
                     { $(e).datepicker({ dateFormat: 'mm/dd/yy' });
                     }, sopt:['eq','ne']}


        },

        {name: 'experience', label: 'Experience', searchoptions:{sopt:['eq','ne']}, align: 'center'},
        {name: 'actions', label: 'Actions', search: false,
        formatter: 'actions', formatoptions:{   
                                    afterSave: myFunction,
        }}
],


    rowNum: 10,
    rowList:[5,10,15],
    pager: '#pager',
    viewrecords: true,
    loadonce:true,
    sortname: 'id',
    caption: "Personal Informations",

    inlineEditing: {

        ajaxSaveOptions: { contentType: "application/json" },
        serializeSaveData: function (postData) {

            return JSON.stringify(postData);
        }
    }

I tried using postData like this (but without any luck):

postData:{  

             username: function(){return grid.jqGrid('getCell', Id, "username")} ,
             email: function(){return grid.jqGrid('getCell', Id, "email")} , 
             experience: function(){return grid.jqGrid('getCell', Id, "experience")} ,

            },

Java code for POST method:

 @POST
 @Path("/post")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)


 public void addElement(String data) throws SQLException{   
     System.out.println(data);
     JsonParser parser = new JsonParser();
     JsonObject addElem =(JsonObject) parser.parse(data);


     String sql = "insert into InternshipBC.dbo.EMPLOYEES values('" + addElem.get("firstname") + "' , '" + addElem.get("surname") + "' , '" + addElem.get("username") + "' , '"
                + addElem.get("email") + "' , '" + addElem.get("chefdepartment") + "' , '" + addElem.get("position") + "' , '" + addElem.get("joinyear") + "' , '" + addElem.get("experience") + "')";

     executeQuery(sql);


 }
public ResultSet executeQuery(String sql){  
     ResultSet result = null;
     Statement st = null;
     try {

           conn = DriverManager.getConnection(DB_URL,USER,PASS);
           st = conn.createStatement();
           result = st.executeQuery(sql);
           conn.close();
     }catch(Exception e){   
         System.out.println(e.getMessage());
     }

     return result;
 }

Any suggestion would be appreciated. Thanks.


Now I use free jqGrid 4.11.0.

jqGrid code:

grid.jqGrid({


    mtype:'GET',
    datatype:'json',
    url:'http://localhost:8080/JDBCapplication/app/test/get',
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8'},
    serializeGridData: function (postdata) {

        return JSON.stringify(postdata);
        },
        jsonReader : {
            root:"rows",
            page: "page",
            total: "total",
            records: "records",
            cell: "",

            repeatitems: false,
         },



    autowidth: true,
    height: 200,
    editurl:'http://localhost:8080/JDBCapplication/app/test/post',
    gridview: true,
    colModel: [ 
        {name: 'id', label: 'Id', width: 150, align: 'center',hidden:true, search:false},  
        {name: 'firstname', label: 'Firstname', align:'center', editable: true, searchoptions:{sopt:['eq','ne','bw','ew','cn','nc']}, editoptions: {defaultValue: ' '},formatter: 'text'}, 
        {name: 'surname', label: 'Surname', align:'center', editable: true, searchoptions:{sopt:['eq','ne','bw','ew','cn','nc']}, editoptions: {defaultValue: ' '},formatter: 'text'}, 

        {name: 'username', label: 'Username', align:'center', editable: "hidden", searchoptions:{sopt:['eq','ne','bw','ew','cn','nc']}}, 
        {name: 'email', label: 'Email', align:'center', editable: "hidden", searchoptions:{sopt:['eq','ne','bw','ew','cn','nc']}}, 
        {name: 'chefdepartment', label: 'Chef Department', editable: true, align: 'center',
        edittype: "checkbox",  formatter: chefdepFunc, editoptions:{ dataEvents: checkboxEdit, value: "Yes:No", defaultValue: 'No'}, 
        stype:'select', searchoptions:{value: "Yes:Yes; No:No",sopt:['eq','ne']}
        }, 
        {name: 'position', label: 'Position', editable: true, align: 'center',
        edittype: "select", formatter: 'select', editoptions:{value: ' : ; Position 1:Position 1; Position 2:Position 2; Position 3:Position 3; Position 4:Position 4; Position 5:Position 5'},
        stype: 'select', searchoptions:{value: ' : ; Position 1:Position 1; Position 2:Position 2; Position 3:Position 3; Position 4:Position 4; Position 5:Position 5', sopt:['eq','ne']}

        },

        {name: 'joinyear', label : 'Join Year', align: 'center', editable: true, editoptions: { size: 20, maxlengh: 10,
            dataInit: function(e) 
                     { $(e).datepicker({ dateFormat: 'mm/dd/yy' });
                     } },
            searchtype:'datepicker', searchoptions:{size: 20, maxlengh: 10,
            dataInit: function(e) 
                     { $(e).datepicker({ dateFormat: 'mm/dd/yy' });
                     }, sopt:['eq','ne']}


        },

        {name: 'experience', label: 'Experience', editable: "hidden", editoptions: {disabled: true} , searchoptions:{sopt:['eq','ne']}, align: 'center'},
        {name: 'actions', label: 'Actions', search: false,
        formatter: 'actions', formatoptions:{   
                                    afterSave: myFunction,
        }} 
],


    rowNum: 10,
    rowList:[5,10,15],
    pager: '#pager',
    viewrecords: true,
    loadonce:true,
    sortname: 'id',
    caption: "Personal Informations",


    inlineEditing: {

        ajaxSaveOptions: { contentType: "application/json" },
        serializeSaveData: function (postData) {


            postData.username= grid.jqGrid("getCell", postData.id,"username"),
            postData.email= grid.jqGrid("getCell", postData.id,"email") , 
            postData.experience= grid.jqGrid("getCell", postData.id, "experience");

            return JSON.stringify(postData);
        }

    },

});

    grid.jqGrid('navGrid', '#pager',{add:false, search: true, searchtext: "Search", refresh: true, refreshtext: "Refresh", del: true, deltext: "Remove", edit: false, save: false, cancel: false},
                {},{},{ 

                    url:'http://localhost:8080/JDBCapplication/app/test/del',
                    mtype: 'DELETE',
                    reloadAfterSubmit: true,
                    ajaxDeleteOptions:{contentType: "application/json"},
                    serializeDeleteData: function(postData){    
                        return JSON.stringify(postData);
                    }
                },{},{},{},{});



    grid.jqGrid('inlineNav', '#pager',{ 
        add: true,
        addicon: "ui-icon-plus",
        addtext: "Add",

        addParams:{ 
        addRowParams:{
        aftersavefunc: myFunction,
                    keys: true,
        },
        position:"last", 
        },
        edit: true,
        editicon: "ui-icon-pencil",
        edittext: "Edit",
        editParams:{
            url: 'http://localhost:8080/JDBCapplication/app/test/edit',
            mtype: 'POST',
            keys: true,
            aftersavefunc: myFunction,

   },
        save: true,
        saveicon: "ui-icon-disk",
        savetext: "Save",
        cancel: true,
        cancelicon: "ui-icon-cancel",
        canceltext: "Cancel",
        search: false,
        refresh: false,
        del:false

    });

});

$(function(){
var grid = $("#grid");

var myFunction = function(Id){

                var firstname, surname, username, email;

                firstname = grid.jqGrid('getCell', Id, "firstname");
                surname = grid.jqGrid('getCell', Id, "surname");
                username = grid.jqGrid('getCell', Id, "username");


                if((firstname=="")&&(surname==""))
                {
                    username="";
                    email="";
                }
                else
                {
                    username = firstname + "." + surname;
                    email = username + "@test.com";
                }

            grid.jqGrid('setCell', Id, "username", username);
            grid.jqGrid('setCell', Id, "email", email);   
checkboxEdit = [
                    {type : 'click', data: {'Yes': 'Yes'}, fn: function (e, id) {
                                   var checkbox = grid.getCol('chefdepartament'),
                                       ids = grid.jqGrid('getDataIDs'),
                                       totalOfCheckedBoxes = [],
                                       k;

                                   for (k = 0; k < ids.length; k++) {
                                           if(checkbox[k] == 'Yes'){
                                               totalOfCheckedBoxes.push(checkbox[k]);
                                               if (totalOfCheckedBoxes.length == 1){
                                                   alert('Chef Deparment already exist!');
                                                   $(this).prop("checked",false);
                                                   totalOfCheckedBoxes = 0;
                                               }
                                           }
                               }
                           }}];


   var chefdepFunc = function(cellvalue, options ,rowObject){
        if(cellvalue == 'Yes'){
            return 'Yes';
        }
        return 'No';
    };

JAVA code:

@GET
 @Path("/get")
 @Produces(MediaType.APPLICATION_JSON)

public ArrayList<Employee>getEmployee() throws SQLException{    
     ArrayList<Employee>collection = new ArrayList<Employee>();
     String sql = "select * from InternshipBC.dbo.EMPLOYEES";
     ResultSet result = executeSelect(sql);
try{
     while(result.next()){  
         Employee employee = new Employee();
         employee.setId(result.getInt("id"));
         employee.setFirstname(result.getString("firstname"));
         employee.setSurname(result.getString("surname"));
         employee.setUsername(result.getString("username"));
         employee.setEmail(result.getString("email"));
         employee.setChefdepartment(result.getString("chefdepartment"));
         employee.setPosition(result.getString("position"));
         employee.setExperience(result.getString("experience"));

         collection.add(employee);

     }
 }catch(Exception e){
        System.out.println(e.getMessage());
    }
         return collection;

}



 @POST
 @Path("/post")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)


 public void addElement(String data) throws SQLException{   
     System.out.println(data);
     JsonParser parser = new JsonParser();
     JsonObject addElem =(JsonObject) parser.parse(data);




     String sql = "insert into InternshipBC.dbo.EMPLOYEES values('" + addElem.get("firstname") + "' , '" + addElem.get("surname") + "' , '" + addElem.get("username") + "' , '"
                + addElem.get("email") + "' , '" + addElem.get("chefdepartment") + "' , '" + addElem.get("position") + "' , '" + addElem.get("joinyear") + "' , '" + addElem.get("experience")+ "')";

     sql = sql.toString().replaceAll("\"", "");

     executeQuery(sql);



 }


 public void uniqueID() throws SQLException{    


     String sql = "INSERT INTO InternshipBC.dbo.EMPLOYEES (firstname, surname, username, email, chefdepartment, position, joinyear, experience) values (?,?,?,?,?,?,?,?)";
     PreparedStatement pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        pst.setString(1, "firstname");
        pst.setString(2, "surname");
        pst.setString(3, "username");
        pst.setString(4, "email");
        pst.setString(5, "chefdepartment");
        pst.setString(6, "position");
        pst.setString(7, "joinyear");
        pst.setString(8, "experience");

     int affectedRows = pst.executeUpdate();

     if(affectedRows == 0){ 
         throw new SQLException("Creating user failed, no rows afected!");
     }

     ResultSet result = pst.getGeneratedKeys();

     if (result != null && result.next()) {
         int id = result.getInt("id");
         System.out.println("Generated id :" + result.getInt("id"));


     } 


 }

 @POST
 @Path("/edit")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public void editElement(String data) throws SQLException{  

     System.out.println(data);
     JsonParser parser = new JsonParser();
     JsonObject editElem =(JsonObject) parser.parse(data);


     String sql = "Update InternshipBC.dbo.EMPLOYEES set firstname = '" + editElem.get("firstname")+ "', surname = '" + editElem.get("surname") + "', username = '" + editElem.get("username") + "', email = '" + editElem.get("email") + "', chefdepartment = '"+ editElem.get("chefdepartment") + "', position = '" + editElem.get("position") + "', joinyear = '" + editElem.get("joinyear") + "', experience = '" + editElem.get("experience")+ "', where id = '"+ editElem.get("id") + "'";


     executeQuery(sql);

 }


 @POST
 @Path("/del")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public void deleteElement(String data){
     System.out.println(data);
     JsonParser parser = new JsonParser();
     JsonObject delElem =(JsonObject) parser.parse(data);


     String sql = "delete from InternshipBC.dbo.EMPLOYEES where id = '" + delElem.get("id")+ "'";

     executeQuery(sql);
 }


 public ResultSet executeQuery(String sql){ 
     ResultSet result = null;
     Statement st = null;
     try {

           conn = DriverManager.getConnection(DB_URL,USER,PASS);
           st = conn.createStatement();
           result = st.executeQuery(sql);
           conn.close();
     }catch(Exception e){   
         System.out.println(e.getMessage());
     }

     return result;
 }

 public ResultSet executeSelect(String sql){    
     ResultSet result = null;
     Statement st = null;
     try {

           conn = DriverManager.getConnection(DB_URL,USER,PASS);
           st = conn.createStatement();
           result = st.executeQuery(sql);
           conn.close();
     }catch(Exception e){   
         System.out.println(e.getMessage());
     }

     return result;
 }

}

When I run the application, in my database (Sql sever), the HTTP POST Request :204 No Content will return:

{"firstname": "Jojo ","surname":"Bobo","username": "","email": "","chefdepartment":"No","position":" Position 3","joinyear":"01/22/2016","experience": ""}

In my console for jqGrid if I execute :

console printscreen for jqGrid

What I want is that the http POST Request to return in database the all values.

2 Answers2

0

If I understand your problem correctly then, I think you want to post your non-editable column values on post call. So you can use following approach,

onclickSubmit: function (options, postdata) {
  var rowid = postdata[this.id + "_id"];
  return {
       username: $(this).jqGrid("getCell", rowid,"username") ,
       email: $(this).jqGrid("getCell", rowid,"email") , 
       experience: $(this).jqGrid("getCell", rowid, "experience")
  };
}

This is already answered with good explanation here

OR

Try this

editable: true, editoptions: {disabled: true}
Community
  • 1
  • 1
amighty
  • 784
  • 4
  • 12
0

I hope that I correctly understand your question.

You don't specified this in your question explicitly, but you use some options which exist in free jqGrid fork of jqGrid. Thus I'd suggest you very simple solution, which works only in free jqGrid too.

The columns username, email and experience are not editable, but I implemented in free jqGrid the possibility to use editable: "hidden" for the columns. After adding the properties in the columns the columns will stay not edible, but the values from the columns will be send to the server.

Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Thanks, Oleg. I used the suggestion of amighty, and my grid returns the values for username, email and experience, but not what I what. It return: – Constantin Lucian Jan 23 '16 at 11:46
  • @ConstantinLucian: Which version of free jqGrid you used in your tests? Do you have the demo, which reproduces the problem? – Oleg Jan 23 '16 at 12:02
  • the extra code: [ inlineEditing: { ajaxSaveOptions: { contentType: "application/json" }, serializeSaveData: function (postData) { postData.username= grid.jqGrid("getCell", postData.id,"username") postData.email= grid.jqGrid("getCell", postData.id,"email") , postData.experience= grid.jqGrid("getCell", postData.id, "experience") return JSON.stringify(postData); } }] , – Constantin Lucian Jan 23 '16 at 12:03
  • and my grid returns the values for username, email and experience, but not what I what. It return: " username: "". How can I change that? By the way, I want to thank you for all your answers that I found on stackoverflow, helped me a lot. – Constantin Lucian Jan 23 '16 at 12:04
  • @ConstantinLucian: You don't need to do this if you set `editable: "hidden"` in the columns. It's important to know which version of free jqGrid you use. The value `` corresponds **`editable: true`** value. **Can you provide the full demo?** – Oleg Jan 23 '16 at 12:08
  • Oleg, I use jqDrid 5.0.1 . – Constantin Lucian Jan 23 '16 at 12:08
  • jqGrid 5.0.1 is [Guriddo jqGrid JS](http://guriddo.net/?page_id=103334). It's commertial version. Free jqGrid is **another fork** of jqGrid which I develop and provide for free like it was for jqGrid <=4.7. You can download free jqGrid from [here](https://github.com/free-jqgrid/jqGrid) or just to use from Internet from CDN. The last option provide very god performance. You need just chnge the URL to jqGrid files. See [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/Access-free-jqGrid-from-different-CDNs) or [the readme](https://github.com/free-jqgrid/jqGrid/blob/master/README.md). – Oleg Jan 23 '16 at 12:13
  • grid.jqGrid({ mtype:'GET', datatype:'json', url:'http://localhost:8080/JDBCapplication/app/test/get', ajaxGridOptions: { contentType: 'application/json; charset=utf-8'}, serializeGridData: function (postdata) { return JSON.stringify(postdata); }, – Constantin Lucian Jan 23 '16 at 12:15
  • Ok. I will make the changes, and I'll keep you in touch. Thanks. – Constantin Lucian Jan 23 '16 at 12:16
  • Hi Oleg. I made all the changes that you said to me.In the meantime, I made something. If I write in the console: $("#grid").jqGrid("getRowData", "jqg1"), after I execute the application, it will return me in the console the all values in a Json string, like this:{"firstname": "Jojo ","surname":"Bobo","chefdepartment":"No","username:" "Jojo.Bobo", email: ''Jojo.Bobo@test.com, "position":" Position 3","joinyear":"09/17/2015", exerience: ''25 days","oper":"add","id":"jqg1"} – Constantin Lucian Jan 25 '16 at 18:34
  • but my HTTP POST Request :204 No Content returns empty string for username, email, experience. Can you help me, please? I don't know what I must do. – Constantin Lucian Jan 25 '16 at 18:37
  • @ConstantinLucian: Sorry, but I can't follow you. Could you append the text of your question with your *current code* and the test data returned from `/JDBCapplication/app/test/get`. You should include which version and fork of jqGrid you use now. After that you should describe what you do to reproduce the problem: for example start inline editing of the first row, modify some field and press Enter. What data you expect to post to the server and what you see in HTTP trace instead (one can use [Fiddler](http://www.telerik.com/fiddler) or Developer Tools of IE/Chrome to trace of HTTP traffic). – Oleg Jan 25 '16 at 18:55
  • Oleg, I edit my question and I put all my code and test data returned in. I use free jqGrid 4.11.0. – Constantin Lucian Jan 25 '16 at 19:46
  • @ConstantinLucian: If you use open source projects should should try to update as soon as possible. If you get errors in the new version you can report it and the bugs will be fixed very quickly. I fix there typically in the same day. You use now free jqGrid 4.11.0, but 4.12.1 is the last one. The feature `editable: "hidden"` for **inline editing** is implemented starting with 4.12.0. The next problem: you don't posted the test data. Moreover I tried to create the demo based on you JavaScript code, but it contains undefined functions like `chefdepFunc`, `checkboxEdit`, `myFunction`, ... – Oleg Jan 25 '16 at 20:19
  • @ConstantinLucian: One can reduce and simplify the code which you use. One can localize your main problem and fix it if one have the demo which can be debugged. You can use https://jsfiddle.net for example to fill the grid with the data, which you return. To simulate loading from the server one can use Echo service of jsfiddle. See https://jsfiddle.net/37rb593h/4/ as an example. If you have your demo online that you can just post the URL – Oleg Jan 25 '16 at 20:26
  • Ok, Oleg. I will use everything you said and make the changes, I will use the free jqGrid 4.12. and try to run. Thanks for all your help and Thanks for being patient with me. I'll keep you in touch. – Constantin Lucian Jan 25 '16 at 20:33
  • @ConstantinLucian: You are welcome! Please use always the latest released version (4.12.1) or the latest code from [RawGit](https://github.com/free-jqgrid/jqGrid/wiki/Access-free-jqGrid-from-different-CDNs#access-githib-code-from-rawgit). If you can't use the latest version then write always which one you use. Try always provide the demo which reproduces the problem. If I can see and debug the problem I find the reason typically in 1-2 min. You can contact me when you will have some progress in your investigations or if you would have the demo which I can access. – Oleg Jan 25 '16 at 20:43