1

I use jqGrid and I loads data from server via AJAX. My data are {id: number, abberaviation: string, rate: float} (Id is same like Id in database). Then I will pass data to jqGrid. User is editing data on page. Then user will click on submit and I want to send data to server, but data has wrong datatypes {id: string, abberaviation: string, rate: string}.

I am getting data via getRowData function and I don't know how to send data with the same datatypes as originally received from the server.

I must retyped all datatypes on right datatypes, which server is expecting. UPDATED params = null notice = null

$(document).ready () ->
    params = JSON.parse $("#params").html()
    notice = $("#notice")
    table = $("#table")
    $.jgrid.no_legacy_api = true
    lastSelectedRowId = null

    table.jqGrid(
        datatype: "clientSide" # load from array in js
        data: params.data # data array
        width: "100%"
        height: "100%"
        colNames: ['','Měna', 'Kurz', 'Akce']
        colModel: [
            {
                index: 'id',
                name: 'id',
                width: 55,
                editable: false,
                sortable: false,
                hidden: true,
            }, {
                index: 'abbreviation',
                name: 'abbreviation',
                width: 90,
                align: "center",
                editable: true,
                sortable: false
            }, {
                index: 'rate',
                name: 'rate',
                width: 100,
                align: "center",
                editable: true,
                sortable: false
            }, {
                name: 'action',
                width: 40,
                align: "center",
                editable: false,
                formatter:'actions',
                fixed: true,
                resize: false,
                formatoptions: { keys: true, editbutton: false }
            }
        ]
        pager: "#status"
        editurl: "clientArray" # data won't be posted to the server but rather is saved only to the grid 
        # sortname: 'id'
        # sortorder: "desc"
        rowList: [] # disable page size dropdown
        pgbuttons: false # disable page control like next, back button
        pgtext: null # disable pager text like 'Page 0 of 10'
        viewrecords: true # show total number of records 'View X to Y out of Z'
        onSelectRow: (rowId) ->
            console.log "rowId #{rowId} #{lastSelectedRowId}"
            if lastSelectedRowId and rowId isnt lastSelectedRowId
                table.jqGrid 'saveRow', lastSelectedRowId
        ondblClickRow: (rowId, iRow, iCol, e) ->
            console.log "rowId #{rowId} #{lastSelectedRowId}"
            if rowId and rowId isnt lastSelectedRowId
                console.log e.target
                table.jqGrid 'editRow', rowId, true
                $("input, select", e.target).focus()
                lastSelectedRowId = rowId
    )

    table.bind("jqGridInlineAfterSaveRow", (e, rowid, orgClickEvent) ->
        console.log "jqGridInlineAfterSaveRow"
        console.log "lastSelectedRowId = null"
        lastSelectedRowId = null
    )

    table.bind("jqGridInlineAfterRestoreRow", (e, rowid, orgClickEvent) ->
        console.log "jqGridInlineAfterRestoreRow"
        console.log "lastSelectedRowId = null"
        lastSelectedRowId = null
    )

    $("#add-row").click (e) ->
        e.preventDefault()
        # table.jqGrid "editCell", 1, 1, false
        table.jqGrid "addRowData", undefined, "last"

    $("#save").click (e) ->
        e.preventDefault()
        showNotice "Probíhá ukládání na server..."
        data = table.jqGrid "getRowData"
        for i in [0...data.length] by 1
            item = data[i]
            item.id = Number item.id
            if item.id is 0
                delete data[i]
            else if item.id is "NaN"
                item.id = null
            item.order = i
            item.rate = Number item.rate
        jsonData = JSON.stringify data

        # $.ajax
        #   url: params.action
        #   type: "POST"
        #   data: token: params.token, data: jsonData
        #   success: (res) ->
        #       token = res.token
        #       console.log res.data
        #       showNotice "Data byla úspěšně uložena."

        #   error: (error) ->
        #       errText = JSON.parse error.responseText
        #       showNotice "Response #{error.status}: #{errText.msg}"
        #       console.log error

showNotice = (msg) ->
    notice.html msg
    notice.parent().removeClass "hidden"
Oleg
  • 220,925
  • 34
  • 403
  • 798
positive
  • 151
  • 2
  • 12
  • You wrote that your problem was *sending the data to the server*, but you don't included the corresponding Ajax call and the code where you prepare the data for sending (the usage of `getRowData` and so on). Could you include the part of your code which is the origin of your problem? – Oleg Dec 18 '14 at 06:49
  • Hi Oleg, I read a few your answers about jqGrid :) I updated my question. And I have also another problem with focus cell after double clicked on row for edit. I found your solving _http://stackoverflow.com/questions/6536654/how-to-edit-the-selected-cell-on-jqgrid/6538102#6538102_, but I think that this solving is not working on 4.7.0 - jQuery Grid and I dont know :( – positive Dec 18 '14 at 10:12
  • Sorry, but jqGrid is jQuery plugin written in JavaScript, but you use unclear dialect of unclear language. The modified code which you posted still have no Ajax call. So I can't help you having the information. Your another question seems to me have no relation with the current one. You should clear formulate what you do and what it your problem in the new question. – Oleg Dec 18 '14 at 10:58
  • Ok, I'll fill all my file. This code is clear dialect, but code is wrote in coffeescript _http://coffeescript.org/_. Ok, I'll create a new post for my second question. My problem is not in AJAX call. Problem is if I print `console.log(table.jqGrid("getRowData"));` so records have parameter ID string datatype but originally records from server had ID like integer datatype. Problem is that jqGrid is converting all datatypes to string. :( – positive Dec 18 '14 at 11:29
  • 1
    Probably there are misunderstanding what is rowid. jqGrid use id property if input items to assign **id** attribute of `` elements which build rows of the grid. The usage of hidden `id` column is redundant. In any way even if you save any data in attribute of HTML page or inside of HTML item you save just a string. No type information will be send. So all data read back from jqGrid are strings too. If you need to change the type before sending to the server you should do this yourself before Ajax call. By the way you have to use `rowNum: 10000` option if you want to display more as 20 rows – Oleg Dec 18 '14 at 11:48
  • 1
    Alternatively you can add `pager` or `toppager: true` option to allows local paging of the data. In any way I strictly recommend you to use `gridview: true` and `autoencode: true` options of jqGrid and to use `datatype: "local"` instead of `datatype: "clientSide"`. I recommend yot to remove all `index` properties from `colModel`. I recommend you to use formetters and column templates (see [here](http://stackoverflow.com/a/6047856/315935)) which bring you in the direction to datatypes in the columns. – Oleg Dec 18 '14 at 11:50
  • Ok, I will try your recommendation. It is true that I don't understand how jqGrid works with IDs. Thank you very much. – positive Dec 18 '14 at 11:55
  • 1
    You are welcome! I recommend you to use Developer Tools of Chrome/Internet Explorer/Firefox and examine `id` attributes of `` elements on your different tests. You should also to consider to use `$("#table").jqGrid("getGridParam", "data")` and `$("#table").jqGrid("getGridParam", "_index")` to get information saved as JavaScript objects instead of HTML DOM elements. `getRowData` data works only with pure HTML page. – Oleg Dec 18 '14 at 12:00
  • _In any way even if you save any data in attribute of HTML page or inside of HTML item you save just a string. No type information will be send._ I think that it is not true, because my server data saved into HTML attribute

    in JSON and I will read of data in JS from `

    {"data":[{"id":1,"abbreviation":"cz","rate":1}, "id":138,"abbreviation":"PL","rate":4}],"token":"INnGNqCx5vFAHXG65q385H-Q4_pCwttJYId-S9nN3QA","action":"\/my\/app_dev.php\/admin\/currency\/"}

    `. In these data is to see that id will be integer if I will execute JSON.parse.
    – positive Dec 18 '14 at 12:05
  • In example library datatypes preserved, but jqGrid no :( But jqGrid is much better – positive Dec 18 '14 at 12:08
  • Oh, I see.. This method `$("#table").jqGrid("getGridParam", "data")` is it what I needed :D Thank you master of jqGrid ;) – positive Dec 18 '14 at 12:20
  • You are welcome! Still be careful about *the type* of properties of `data` after modification of the data. – Oleg Dec 18 '14 at 12:22
  • Noooo, this method is ok only if I dont modify data. If I will modify data, then parameters id is string and rate also :/ – positive Dec 18 '14 at 12:28

1 Answers1

1

After a long discussion of your problem I could understand that the origin of your problem is changing of type of JavaScript data of local data parameter. You use inline editing to edit the data. So you can use aftersavefunc callback to fix the problem.

I prepared the demo which demonstrates the solution. You can validate that $grid.jqGrid("getGridParam", "data"); will returns modified data where the types of the data are not changes. The property closed of the modified data will stayboolean and the properties tax, amount and total will be stay numbers. The code of aftersavefunc used as editRow parameter is the following:

aftersavefunc: function (rowid, resp, tmp, o) {
    var rowItem = $(this).jqGrid("getLocalRow", rowid);
    rowItem.closed = rowItem.closed === "Yes";
    rowItem.tax = parseFloat(rowItem.tax);
    rowItem.amount = parseFloat(rowItem.amount);
    rowItem.total = parseFloat(rowItem.total);
}
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Hi, this solution seems to be the best. But if I put into amount property decimal number with separator ',' then parseFloat throws error. How to solve it ? – positive Dec 19 '14 at 13:39
  • 1
    @positive: I find the simplest solution is replacing thousand separator to empty string and then replacing the decimal separator to `"."`. If no thousand separator will be used and `,` will be used as decimal separator then you can do something like `parseFloat(String(rowItem.amount).replace(",", "."))`. Alternatively you can use [globalize](https://github.com/jquery/globalize) plagin to parse numbers. See [the answer](http://stackoverflow.com/a/10245286/315935). – Oleg Dec 19 '14 at 13:57
  • Ok, thank you very much and your demos are very useful. I will play with it. Look at solution, which I found for cell focus for version 4.7.0. [LINK](http://stackoverflow.com/questions/27548985/jqgrid-how-to-focus-cell-inline-editing/27549615#27549615) – positive Dec 19 '14 at 14:03
  • 1
    @positive: You are welcome! I would recommend you to use `focusField` option too. You should be only carefully with the value of it. Don't use any static value and search `colModel` for the specific `name` property. The index of the `colModel` item with the `name` is what you need to use. Do index calculation **directly** before the usage of `editRow`. Think about possible changing of the order of columns because of `columnChooser` or the usage of `sortable: true` option of jqGrid which allows the user to change the order of columns using drag and drop of the column headers. – Oleg Dec 19 '14 at 14:30
  • @positive: I recommend you to read [the post](http://meta.stackexchange.com/a/5213/147495) which describes that you have right to vote up 30 answers or questions **per day**. Voting is the most important right which *gives tips to the search engine*. So to help other people to find the question and the answer **I recommend you to vote up all helpful information which you find on the stackoverflow**. You will help in the way other users. – Oleg Dec 19 '14 at 14:46