0

i have problem with decode JSON data. actually i want slickgrid work to save in mysql. so, i read [question]:Saving Changes in SlickGrid with php but don't know how to decode the data.

here is my PHP script to process the JSON:

    <script src="jquery-1.7.min.js"></script>
    <script type="text/javascript" src="jquery.json.js"></script>
    <?php

    if(isset($_POST['dataz']))
    {
        ?>
<!--this isn't working-->
        <script>
        var obj = $.JSON.decode(input[name='dataz'].val());
        alert('json decode : '+obj);
        </script>
        <?php
//this produce nothing
        echo json_decode($_POST['dataz']);
        var_dump(($_POST['dataz']));
    }
    else
    {
        echo "No data.";
    }
    ?>

and this is the JSON i tried to decode

...
<form action="proses.php" method="POST">
  <input type="submit" value="Save">
  <input type="hidden" name="dataz" value="">
</form>
<script>
  $(function() {
    $("form").submit(
      function() {
        $("input[name='dataz']").val($.JSON.encode(data));
      }
    );
  });
</script>
Community
  • 1
  • 1
Bari
  • 88
  • 3
  • 15
  • If it is *only* about how to parse JSON, this was answered here: http://stackoverflow.com/q/4935632/218196. However, this is probably not your only issue. – Felix Kling Mar 20 '13 at 09:47
  • Do you have to specifically use JSON for that? Because the way I have it done with MySQL is with the event `grid.onCellChange.subscribe(function(e,args) { $.post...` not using any JSON for that, though I return problems in JSON as callback, which by the way you might not have any return feedback with a form submit. If you need further help, I'll post an "answer" – ghiscoding Mar 20 '13 at 14:47
  • @ghiscoding: can you share the code? – Bari Mar 21 '13 at 01:52

1 Answers1

0

Alright here is my code for inserting, updating, deleting from SlickGrid to MySQL

    var ajaxFileURL = "fileAjax.php?action=list";   

function populateList(ajaxFileURL) {    
    var msgDelete = 'Do you really want to delete the row?';
    var deleteIcon = "<img src='/images/delete.png' border='0' />";

    // attach the delete event on the ID column
    var columns = [     
        {id:"id", name:"ID", field:"id", width:8, formatter: function (r,c,id,def,datactx){ return "<a href='#' onclick='if (confirm(\""+msgDelete+"\")) removeClick(\""+ajaxFile+"\",\""+id+"\","+r+")'>"+deleteIcon+"</a>";}},
        {id: "title", name: "Title", field: "title", width: 70, minWidth: 50, cssClass: "cell-title", sortable: true, editor: Slick.Editors.Text}
    ];
    var options = {
        enableCellNavigation: true,
        editable: true
    };

    $.getJSON(ajaxFileURL, function (ServerResponse) {
        var groupItemMetadataProvider = new Slick.Data.GroupItemMetadataProvider();
        dataView = new Slick.Data.DataView({
            groupItemMetadataProvider: groupItemMetadataProvider,
            inlineFilters: true
        });
        grid = new Slick.Grid("#myGrid", dataView, columns, options);

        // This section treats the INSERT/UPDATE
        grid.onCellChange.subscribe(function(e,args) {
            //dataView.updateItem(args.item.id,args.item);
            if (typeof(args.item.id)=='undefined')
                $.post(ajaxFileURL+"?action=insert", args.item);
            else{
                $.post(ajaxFileURL+"?action=update", args.item, function(ServerResponseUpt){
                    // if database return an error then display it to the user and undo the cell change
                    if(parseInt(ServerResponseUpt.affected_rows) < 1 || ServerResponseUpt.error_msg != "") {
                        alert("UPDATE ERROR: "+ServerResponseUpt.error_msg);
                        args.item[ previousCellNames[0] ] = previousCellValues[0];
                        grid.updateRow(args.row);
                        grid.updateRowCount();
                        grid.render();
                    }
                    previousCellNames = new Array();
                    previousCellValues = new Array();
                }, "json");

                // refresh the data on grid
                grid.updateRow(args.row);
                grid.updateRowCount();
                grid.render();
            }
        }); 
        // initialize the model after all the events have been hooked up
        dataView.beginUpdate();
        dataView.setItems(ServerResponse.data);
        dataView.endUpdate();
    } // end of $.getJSON()
} // end of populateList()

// outside function to DELETE
function removeClick(ajaxFileURL, dbRowId, gridRow) {
    $.post( ajaxFileURL+'?action=delete', {id:dbRowId} );
    var item = dataView.getItem(gridRow);//RowNum is the number of the row
    var rowID = item.id
    dataView.deleteItem(rowID);//RowID is the actual ID of the grid row and not the DB row 
    grid.invalidate();
    grid.render();
} 

I'm guessing you already know how to deal with the PHP Ajax file to load data, so just modify the same file to deal with INSERT/DELETE/UPDATE and List... All my action functions are returning JSON, including my grid data. A quick look at my AJAX PHP file would be:

    <?php
switch($_GET['action']) {
    case 'delete':  deleteItem($_POST['id']);
                    break;
    case 'list':    populateList();
                    break;
    case 'update':  updateData();
                    break;
    default:        break;
}

/** Delete an item from the list/DB
 * @param int $id: id number of the item
 */
function deleteItem($id) {
    try{
        // Make the MySQL connection and save it into a global variable
        $mysql = new mysqlDB();
        $mysql->connect();

        // Pull the computer name of the Combo Computer (if exist)
        $sqlDel = sprintf("DELETE FROM table WHERE id='%s'", $id);
        $resultDel = $mysql->query($sqlDel);

        // close the MySQL connection
        $mysql->disconnect();

        print '{ "affected_rows" : '.$resultDel.', "error_msg" : "" }';
    }catch(Error $e){
        print '{ "affected_rows" : 0, "error_msg" : "'.$e->getErrorString().'" }';
    }
}

/** Populate the list with data */
function populateList() {
    try{
        // Make the MySQL connection and save it into a global variable
        $mysql = new productionDB();
        $mysql->connect();
        $mysqli = $mysql->getMysqliObj();
        $mysqli->set_charset("utf8");

        $sqlTable = "SELECT id, title FROM table";
        $result = $mysql->query($sqlTable);

        while( $row = $result->fetch_object() ) {
            $tabData[] = array( "id" => $row->id,
                                "title" => $row->title
                            );
            $nbRows = $result->num_rows; // how many rows does the table have in total?
        }

        // close the MySQL connection
        $mysql->disconnect();

        // Fill the JSON String with the BOM Header info
        $jsonStr .= '{"data":'.json_encode($tabData).',"info" : { "rows" : "'.$nbRows.'"}}';

        print $jsonStr;
    }catch(Error $e){
        print '{ "affected_rows" : 0, "error_msg" : "'.$e->getErrorString().'" }';
    }
}


/** Update some data on the DB */
function updateData() {
    try{
        // Make the MySQL connection and save it into a global variable
        $mysql = new productionDB();
        $mysql->connect();
        $mysqli = $mysql->getMysqliObj();
        $mysqli->set_charset("utf8");

        $groups = '';
        $groupSet = $_POST['defect_group'];
        if( isset($groupSet) ) {
            if( is_array($groupSet) ) {
                foreach($groupSet AS $group) {
                    $groups .= $group.",";
                }
                $groups = substr($groups, 0, -1); // remove last unused comma ","
            }
            else {
                $groups = $groupSet;
            }
        }

        // then make the UPDATE on the table
        $sqlUpdate = sprintf('UPDATE title="%s", WHERE id=%d',
                            $mysqli->real_escape_string($_POST['title'])
                            $_POST['id']
                            );
        $result = $mysql->query($sqlUpdate);

        // close the MySQL connection
        $mysql->disconnect();

        print '{ "affected_rows" : '.$result.', "error_msg" : "" }';
    }catch(Error $e){
        print '{ "affected_rows" : 0, "error_msg" : "'.$e->getErrorString().'" }';
    }
}

That should be enough to put you on road... Enjoy :)

ghiscoding
  • 12,308
  • 6
  • 69
  • 112
  • actually i load data with array format, not json. so would u mind if you share complete code. yup, im not good @ javascript. – Bari Mar 22 '13 at 06:43
  • I added the rest of the PHP side, hopefully you have enough with this, because that is quite complete now... If you need more help on the javascript side, you should take a look at the slickgrid examples code. Loading data as array is not far out, simply encode it in JSON and you're good to go... see my PHP example – ghiscoding Mar 22 '13 at 20:06
  • actually im trying to make it work, i told u im not good in javascript. it's still hard for me to read the code. maybe i need a working demo. which run on PHP. i still dig at it. – Bari Mar 28 '13 at 08:29
  • great, finally i can make it work but for insert and update. yeah, need long time to do that for me. but i'm still curious how to delete? this is my code http://pastebin.com/BMKRutE8 – Bari Mar 28 '13 at 09:21
  • Sorry my example wasn't complete, lot of code when starting from scratch... I edited my code on top, you need to declare the `dataview` object (see in my code right after `$.getJSON` and bind the data which is at the end of the `$.getJSON` add this to your code instead of looping the way you did. Then I also modified the `removeClick()` function, I'm using multiple grid and you're not (I changed grid1 to grid, less confusing). – ghiscoding Mar 29 '13 at 19:09
  • For the Delete, in your code where you declare the columns `{id: "id", ...` add this formatter to the end of your ID column `formatter: function (r,c,id,def,datactx){ return ""+deleteIcon+"";}` for that again you can see my code on top. Hopefully that will it it work for you... If you got it working please accept my answer and vote, if you have more questions add another comment :) Letting me see your full code is a great idea – ghiscoding Mar 29 '13 at 19:11
  • ok, i will trying to add delete in the table. however,i guess the question is answered "how to save data to mysql". even it still need time to make it work. so, thanks. – Bari Apr 01 '13 at 01:30