Author Topic: No grid data using the inline editing example  (Read 21563 times)

Robert

  • Pro Economy
  • Newbie
  • *
  • Posts: 26
    • View Profile
No grid data using the inline editing example
« on: April 04, 2014, 05:07:23 am »
Hello,

I am new to ParamQuery Pro ... I am using the inline editing example and am not understanding how to get the grid populated with data. The php code IS generating valid JSON.

I am suspect it has to do with the get Data in the dataModel but the example simply shows the url: as a path to the php file and getData: as I have my code below:

dataModel: {
            dataType: "JSON",
            location: "remote",
            recIndx: "songID",
            url: "/data/songs_DA.php",
            //url: "/pro/products.php",//for PHP
            getData: function (response) {
                return { data: response.data, curPage: response.curPage, totalRecords: response.totalRecords };
            }

Any suggestions?

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6200
    • View Profile
Re: No grid data using the inline editing example
« Reply #1 on: April 04, 2014, 09:43:51 am »
put an alert box, break point or console.log in the getData callback and check the output.

open up the firebug or chrome console and check for any JSON parsing errors.


Robert

  • Pro Economy
  • Newbie
  • *
  • Posts: 26
    • View Profile
Re: No grid data using the inline editing example
« Reply #2 on: April 05, 2014, 05:43:22 am »
I am sorry to be such a newbie ... below is my code. It is copied from the inline editing example and slightly modified to suit my data. The echo from the PHP file produces a JSON object in the exact format as used in the example from the site. Could someone please look through my code below and see if there is something there I have messed up?

Here is my JS:

$(function () {
   
    //define common ajax object for addition, update and delete.
    var ajaxObj = {
        dataType: "JSON",
        beforeSend: function () {
            this.pqGrid("showLoading");
        },
        complete: function () {
            this.pqGrid("hideLoading");
        },
        error: function () {
            this.pqGrid("rollback");
        }
    };
    //to check whether any row is currently being edited.
    function isEditing($grid) {
        var rows = $grid.pqGrid("getRowsByClass", { cls: 'pq-row-edit' });
        if (rows.length > 0) {
            //focus on editor if any
            $grid.find(".pq-editor-focus").focus();
            return true;
        }
        return false;
    }
    //called by add button in toolbar.
    function addRow($grid) {
        if (isEditing($grid)) {
            return false;
        }
        //append empty row in the first row. 
//alert("in add row");
        var rowData = { band: "new", active: 1, title: "new", artist: "new", song_length: "00:00", mp3_link: "new"}; //empty row template
        $grid.pqGrid("addRow", { rowIndxPage: 0, rowData: rowData });
 
        var $tr = $grid.pqGrid("getRow", { rowIndxPage: 0 });
        if ($tr) {
            //simulate click on edit button.
            $tr.find("button.edit_btn").click();
        }
    }
    //called by delete button.
    function deleteRow(rowIndx, $grid) {
        $grid.pqGrid("addClass", { rowIndx: rowIndx, cls: 'pq-row-delete' });
        var rowData = $grid.pqGrid("getRowData", { rowIndx: rowIndx });
        var ans = window.confirm("Are you sure to delete row No " + (rowIndx + 1) + "?");
 
        if (ans) {
            $grid.pqGrid("deleteRow", { rowIndx: rowIndx, effect: true });
 
            var SongID = $grid.pqGrid("getRecId", { rowIndx: rowIndx });
 
            $.ajax($.extend({}, ajaxObj, {
                context: $grid,
//                url: "/pro/products/delete",
                url: "data/songs_DA.php?pq_delete=1", //for PHP
                data: { SongID: SongID },
                success: function () {
                    $grid.pqGrid("commit");
                    $grid.pqGrid("refreshDataAndView");
                },
                error: function () {
                    //debugger;
                    $grid.pqGrid("removeClass", { rowData: rowData, cls: 'pq-row-delete' });
                    $grid.pqGrid("rollback");
                }
            }));
        }
        else {
            $grid.pqGrid("removeClass", { rowIndx: rowIndx, cls: 'pq-row-delete' });
        }
    }
    //called by edit button.
    function editRow(rowIndx, $grid) {
 
        $grid.pqGrid("addClass", { rowIndx: rowIndx, cls: 'pq-row-edit' });
        $grid.pqGrid("editFirstCellInRow", { rowIndx: rowIndx });
 
        //change edit button to update button and delete to cancel.
        var $tr = $grid.pqGrid("getRow", { rowIndx: rowIndx }),
            $btn = $tr.find("button.edit_btn");
        $btn.button("option", { label: "Update", "icons": { primary: "ui-icon-check"} })
            .unbind("click")
            .click(function (evt) {
                evt.preventDefault();
                return update(rowIndx, $grid);
            });
        $btn.next().button("option", { label: "Cancel", "icons": { primary: "ui-icon-cancel"} })
            .unbind("click")
            .click(function (evt) {
                $grid.pqGrid("quitEditMode");
                $grid.pqGrid("removeClass", { rowIndx: rowIndx, cls: 'pq-row-edit' });
                $grid.pqGrid("refreshRow", { rowIndx: rowIndx });
                $grid.pqGrid("rollback");
            });
    }
    //called by update button.
    function update(rowIndx, $grid) {
        if (!$grid.pqGrid("saveEditCell")) {
            return false;
        }
 
        var rowData = $grid.pqGrid("getRowData", { rowIndx: rowIndx });
        var isValid = $grid.pqGrid("isValid", { rowData: rowData }).valid;
        if (!isValid) {
            return false;
        }
        var isDirty = $grid.pqGrid("isDirty");
        if (isDirty) {
            var recIndx = $grid.pqGrid("option", "dataModel.recIndx");
 
            $grid.pqGrid("removeClass", { rowIndx: rowIndx, cls: 'pq-row-edit' });
 
            var url;
            if (rowData[recIndx] == null) {
                //url to add records.
//                url = "/pro/products/add";
                url = "data/songs_DA.php?pq_add=1"; //for PHP
            }
            else {
                //url to  update records.
//                url = "/pro/products/update";
                url = "data/songs_DA.php?pq_update=1"; //for PHP
            }
            $.ajax($.extend({}, ajaxObj, {
                context: $grid,
                url: url,
                data: rowData,
                success: function (response) {
                    var recIndx = $grid.pqGrid("option", "dataModel.recIndx");
                    if (rowData[recIndx] == null) {
                        rowData[recIndx] = response.recId;
                    }
                    $grid.pqGrid("removeClass", { rowIndx: rowIndx, cls: 'pq-row-edit' });
                    $grid.pqGrid("commit");
                }
            }));
        }
        else {
            $grid.pqGrid("quitEditMode");
            $grid.pqGrid("removeClass", { rowIndx: rowIndx, cls: 'pq-row-edit' });
            $grid.pqGrid("refreshRow", { rowIndx: rowIndx });
        }
    }
    //define the grid.
    var obj = {
        width: 900,
        height: 400,
        freezeCols: 3,
        wrap: false,
        hwrap: false,
        resizable: true,
        columnBorders: true,
        sortable: true,
        numberCell: { show: false },
        track: true, //to turn on the track changes.
        flexHeight: false,
        toolbar: {
            items: [
                { type: 'button', icon: 'ui-icon-plus', label: 'Add New Song', listeners: [
                    { "click": function (evt, ui) {
                        var $grid = $(this).closest('.pq-grid');
                        addRow($grid);
                        //debugger;
                    }
                    }
                ]
                }
            ]
        },
        scrollModel: {
            autoFit: false
        },
        selectionModel: {
            type: 'row'
        },
        hoverMode: 'row',
        editModel: {
            saveKey: $.ui.keyCode.ENTER
        },
        editor: { type: 'textbox', select: true },
        validation: {
            icon: 'ui-icon-info'
        },
        title: " still no worky",
 
        colModel: [
                    { title: "", editable: false, minWidth: 172, sortable: false, render: function (ui) {
                        return "<button type='button' class='edit_btn'>Edit</button>\
                                <button type='button' class='delete_btn'>Delete</button>";}},
                    { title: "ID", minWidth: 28, dataType: "integer", align: "center", dataIndx: "songID", editable: false },
                    { title: "Title", width: 125, dataType: "string", align: "left", dataIndx: "title" },
                    { title: "Band", width: 100, dataType: "string", align: "left", dataIndx: "band", editable: false },
                    { title: "Active", width: 5, dataType: "string", align: "center", dataIndx: "active", render: function (ui) {
                        return "<input type='checkbox' />";}},
                    { title: "Artist", width: 125, dataType: "string", align: "left", dataIndx: "artist"},
                    { title: "Length", width: 100, dataType: "string", align: "left", dataIndx: "song_length"},
                    { title: "MP3", width: 100, dataType: "string", align: "left", dataIndx: "mp3_link"},
                   
                    { title: "User 1", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_1"},
                    { title: "User 2", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_2"},
                    { title: "User 3", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_3"},
                    { title: "User 4", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_4"},
                    { title: "User 5", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_5"},
                    { title: "User 6", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_6"},
                    { title: "User 7", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_7"},
                    { title: "User 8", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_8"},
                    { title: "User 9", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_9"},
                    { title: "User 10", width: 100, dataType: "string", align: "left", dataIndx: "user_defined_10"}
                    ],         
     
        dataModel: {
            dataType: "JSON",
            location: "remote",
            recIndx: "songID",
            method: "GET",
            url: "data/songs_DA.php",
            getData: function (response) {
//                alert(response.data[0]);
                alert("here");
                return { data: response.data, curPage: response.curPage, totalRecords: response.totalRecords };
            }
        },
        pageModel: { type: "remote" },
        //save the cell when cell loses focus.
        quitEditMode: function (evt, ui) {
            var $grid = $(this);
            if (evt.keyCode != $.ui.keyCode.ESCAPE) {
                $grid.pqGrid("saveEditCell");
            }
        },
        //make rows editable selectively.
        editable: function (ui) {
            var $grid = $(this);
            var rowIndx = ui.rowIndx;
            if ($grid.pqGrid("hasClass", { rowIndx: rowIndx, cls: 'pq-row-edit' }) == true) {
                return true;
            }
            else {
                return false;
            }
        },
        //use refresh event to display jQueryUI buttons and bind events.
        refresh: function () {
            //debugger;
            var $grid = $(this);
            if (!$grid) {
                return;
            }
            //delete button
            $grid.find("button.delete_btn").button({ icons: { primary: 'ui-icon-close'} })
            .unbind("click")
            .bind("click", function (evt) {
                if (isEditing($grid)) {
                    return false;
                }
                var $tr = $(this).closest("tr"),
                    rowIndx = $grid.pqGrid("getRowIndx", { $tr: $tr }).rowIndx;
                deleteRow(rowIndx, $grid);
            });

            //edit button
            $grid.find("button.edit_btn").button({ icons: { primary: 'ui-icon-pencil'} })
            .unbind("click")
            .bind("click", function (evt) {
                if (isEditing($grid)) {
                    return false;
                }
                var $tr = $(this).closest("tr"),
                    rowIndx = $grid.pqGrid("getRowIndx", { $tr: $tr }).rowIndx;
                editRow(rowIndx, $grid);
                return false;
            });
 
            //rows which were in edit mode before refresh, put them in edit mode again.
            var rows = $grid.pqGrid("getRowsByClass", { cls: 'pq-row-edit' });
            if (rows.length > 0) {
                var rowIndx = rows[0].rowIndx;
                editRow(rowIndx, $grid);
            }
        },
        cellBeforeSave: function (evt, ui) {
            var $grid = $(this);
            var isValid = $grid.pqGrid("isValid", ui);
            if (!isValid.valid) {
                //evt.preventDefault();                   
                return false;
            }
        }
    };

    $("#songs_grid").pqGrid(obj);
});


Here is my PHP:

<?php

//require_once('config.php');
if( isset($_GET["pq_add"]))   
{
    session_start();   
    $songs = json_decode($_SESSION["Songs"], true);
   
//    showDebug($songs);
//   
    //sort by song ID to get max songID
    usort($songs, function($a, $b)
    {
        return ($a["songID"] > $b["songID"]);
    });   
    $max = $songs[sizeof($songs)-1]["songID"];   
     
    $song2=array();   
    $song2["songID"] = $max+1;
    $song2["band"]=$_GET["band"];
    $song2["active"]=$_GET["active"];
    $song2["title"]=$_GET["title"];
    $song2["artist"]=$_GET["artist"];
    $song2["song_length"]=$_GET["song_length"];
    $song2["mp3_link"]=$_GET["mp3_link"];
    $song2["user_defined_1"]=$_GET["user_defined_1"];
    $song2["user_defined_2"]=$_GET["user_defined_2"];
    $song2["user_defined_3"]=$_GET["user_defined_3"];
    $song2["user_defined_4"]=$_GET["user_defined_4"];
    $song2["user_defined_5"]=$_GET["user_defined_5"];
    $song2["user_defined_6"]=$_GET["user_defined_6"];
    $song2["user_defined_7"]=$_GET["user_defined_7"];
    $song2["user_defined_8"]=$_GET["user_defined_8"];
    $song2["user_defined_9"]=$_GET["user_defined_9"];
    $song2["user_defined_10"]=$_GET["user_defined_10"];
         
    $songs[]=$song2;//add new song
    $_SESSION["Songs"]= json_encode($songs);   
    echo "{\"recId\": \"" . $song2["songID"] . "\"}";
}
else if( isset($_GET["pq_update"]))   
{
    session_start();   
    $song2=array();
    $SongID = $song2["songID"] = $_GET["songID"];
    $song2["band"]=$_GET["band"];
    $song2["active"]=$_GET["active"];
    $song2["title"]=$_GET["title"];
    $song2["artist"]=$_GET["artist"];
    $song2["song_length"]=$_GET["song_length"];
    $song2["mp3_link"]=$_GET["mp3_link"];
    $song2["user_defined_1"]=$_GET["user_defined_1"];
    $song2["user_defined_2"]=$_GET["user_defined_2"];
    $song2["user_defined_3"]=$_GET["user_defined_3"];
    $song2["user_defined_4"]=$_GET["user_defined_4"];
    $song2["user_defined_5"]=$_GET["user_defined_5"];
    $song2["user_defined_6"]=$_GET["user_defined_6"];
    $song2["user_defined_7"]=$_GET["user_defined_7"];
    $song2["user_defined_8"]=$_GET["user_defined_8"];
    $song2["user_defined_9"]=$_GET["user_defined_9"];
    $song2["user_defined_10"]=$_GET["user_defined_10"];
             
    $songs = json_decode($_SESSION["Songs"], true);       
    foreach($songs as $i => $song){
        if($song["songID"] == $SongID){           
            $songs[$i] = $song2;
        }       
    }   
    $_SESSION["Songs"]= json_encode($songs);   
    echo "{\"result\": \"success\"}";
}
else if( isset($_GET["pq_delete"]))   
{
    session_start();
    $SongID = $_GET["songID"];
    $songs = json_decode($_SESSION["Songs"], true);   
    foreach($songs as $i => $song){
        if($song["songID"] == $SongID){           
            unset($songs[$i]);
        }       
    }
    $_SESSION["Songs"]= json_encode($songs);   
    echo "{\"result\": \"success\"}";
}   
else{
//    session_start();
    if (isset($_SESSION["Songs"])==false)
    {
        //add in session["Songs"];
        $sql = "SELECT * FROM `songs` WHERE `band` = '".$_SESSION['cur_user']->getBand()."'";     
        $dsn = 'mysql:host='.'localhost'.';dbname='.'Setlist_Manager_DB';
        $options = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
        );
        $dbh = new PDO($dsn, 'root', '', $options);
        $stmt = $dbh->prepare($sql);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
 
        $_SESSION["Songs"]= json_encode($rows);
    }   
    $songs = json_decode($_SESSION["Songs"], true);
    if(isset($_GET["pq_curpage"]) && isset($_GET["pq_rpp"]) )
    {
        $pq_curPage = $_GET["pq_curpage"];
        $pq_rPP=$_GET["pq_rpp"];
         
        $total_Records = sizeof($songs);
 
        $skip = ($pq_rPP * ($pq_curPage - 1));
 
        if ($skip >= $total_Records)
        {           
            $pq_curPage = ceil($total_Records / $pq_rPP);
            $skip = ($pq_rPP * ($pq_curPage - 1));
        }   
        //sort by song title name
        usort($songs, function($a, $b)
        {
            return strcmp($a["Title"], $b["Title"]);
        });
        $songs2=array();
        for( $i=$skip; $i<($skip+$pq_rPP); $i++ ){
            if($i>=$total_Records){
                break;
            }
            $songs2[]=$songs[$i];
        }
        $sb = "{\"totalRecords\":" . $total_Records . ",\"curPage\":" . $pq_curPage . ",\"data\":".json_encode($songs2)."}";
        echo $sb;
    }   
    else{
        $sb = "{\"data\":".json_encode($songs)."}";
        echo $sb;       
    }
}

Here is my HTML:

<div id="songs_grid" style="margin:auto;"></div>

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6200
    • View Profile
Re: No grid data using the inline editing example
« Reply #3 on: April 05, 2014, 09:28:15 am »
Robert

I see you have put an alert box in the getData method. Please share what did you get. If you don't see the alert then please check the url.

try to open the url in a browser, save the output in a file and share as attachment.

Robert

  • Pro Economy
  • Newbie
  • *
  • Posts: 26
    • View Profile
Re: No grid data using the inline editing example
« Reply #4 on: April 05, 2014, 06:59:18 pm »
Thank you for the response. I do not see anything from the alert in the getData method. I have tried using an absolute path to the grid's php file. I have attached a couple screen snips to show what I see, what the grid displays and the json that gets echo'd to the page.

Thank you again for continuing to help me get started with this.


paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6200
    • View Profile
Re: No grid data using the inline editing example
« Reply #5 on: April 06, 2014, 11:43:00 am »
Since it's a response to an AJAX request, there should not be any output ( by echo, print or any other output function) either preceding or following echo $sb

You should not see anything besides JSON data when you type the url in the browser's address bar.  For example

output with remote paging
http://paramquery.com/pro/products/getP?pq_datatype=JSON&pq_curpage=1&pq_rpp=10&_=1396762877547

output without remote paging ( all data at once )
http://paramquery.com/pro/products/get


Robert

  • Pro Economy
  • Newbie
  • *
  • Posts: 26
    • View Profile
Re: No grid data using the inline editing example
« Reply #6 on: April 06, 2014, 09:08:24 pm »
Thank you again for the support. Obviously, I am new to this and am trying to wrap my head around it. Since I am using the specific code from the inline example I was hoping to be able to see this work and learn. BUT, it seems I have missed some critical.

Since the echo IS producing output from the PHP file, the only thing that executes in that PHP script is the new session call when it hits the database AND it is not an AJAX request. I assume then, that no AJAX requests are executing properly.

Do you suspect that my issue is still a problem with the path in the url:?

Or is there something else in the code I have messed up?

Thank you!


paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6200
    • View Profile
Re: No grid data using the inline editing example
« Reply #7 on: April 06, 2014, 11:18:57 pm »
Robert

I'm unable to narrow down the problem in your case unless you follow the instructions exactly as mentioned:

1) Please use absolute url to the PHP file in the dataModel url parameter instead of "data/songs_DA.php".

2) comment the line in js code where it says pageModel: { type: "remote" }.

3) Refresh the grid and see whether it populates.

4) type the absolute url used in step 1 in the address bar of browser, right click on the page, select "view source", save the output in a txt file and kindly post it as attachment.

Robert

  • Pro Economy
  • Newbie
  • *
  • Posts: 26
    • View Profile
Re: No grid data using the inline editing example
« Reply #8 on: April 07, 2014, 02:33:40 am »
I followed your instructions and used the path http://localhost/Php_Setlist_Manager/data/songs_DA.php in step 1.

I commented out "pageModel:" in step 2.

Refreshed the grid and got the same results as before.

Attached is the view source of the absolute path from step one.

Thank you for your continued guidance ...


paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6200
    • View Profile
Re: No grid data using the inline editing example
« Reply #9 on: April 07, 2014, 03:57:19 pm »
your script and output from PHP file has been tested and it works fine.

Please ensure you are using right version of jQuery, jQueryUI. If you are using other js scripts in the page, remove them or test pqGrid in isolation.

Please add error property to your dataModel as below. From your screenshot it looks like you are using IE so I'm writing steps for IE, if it's not IE please specify.

Open the developer tools by pressing F12 or from the menu.

Start debugging the script and refresh the page.
Take note of any alert message and log message in the console,

Go to network tab, start capturing, refresh the page and note down the logs. Also capture all the details from detailed view.

Code: [Select]
        dataModel: {
            dataType: "JSON",
            location: "remote",
            recIndx: "songID",
            method: "GET",
            url: "songs.json",
            error: function(jq){
                alert("jq error");               
                console.log(JSON.stringify(jq));
                //debugger;
            },
            getData: function (response) {
//                alert(response.data[0]);
                alert("here");
                return { data: response.data, curPage: response.curPage, totalRecords: response.totalRecords };
            }
        },
« Last Edit: April 07, 2014, 03:59:28 pm by paramquery »

Robert

  • Pro Economy
  • Newbie
  • *
  • Posts: 26
    • View Profile
Re: No grid data using the inline editing example
« Reply #10 on: April 08, 2014, 02:19:42 am »
THANK YOU for your continued help.

I am, in fact, using other javascript on the page. Specifically, to update header data in the page. The grid itself resides in a DIV content holder on the index page. I am currently using the script below to update the header DIV and I suspect the combination of these 2 things has been my NEWBIE issue all along. It will take me a little time to restructure things and test without the code below. I will update this thread when I do.

function refreshHeaderDiv(head){
    var xmlhttp;
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("header").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","header_div_calls.php?head="+head,true);
    xmlhttp.send();
}

Robert

  • Pro Economy
  • Newbie
  • *
  • Posts: 26
    • View Profile
Re: No grid data using the inline editing example
« Reply #11 on: April 08, 2014, 08:49:59 am »
OH! I am such an idiot. The response body was including a comment I had at the top of my song_DA.php file. Once I removed that, the grid loaded fine. THANK YOU for your patience with me. I learned a great deal here.