Let jqGrid consume JSON

The new jqGrid 3.6 has a jsonReader as Function feature, I couldn’t make it work, possible reason might be my JSON data from WebService doesn’t have ID column at all.

Instead I created an adapter to re-format JSON data to jqGrid specification:

<script type="text/javascript">
    var demo_data =
        "{" +
        "total: '1'," +
        "page: '1'," +
        "records: '5'," +
        "rows : [" +
        "{id:'1', cell:['cell11','cell12','cell13']}," +
        "{id:'2', cell:['cell21','cell22','cell23']}," +
        "{id:'3', cell:['cell31','cell32','cell33']}," +
        "{id:'4', cell:['cell41','cell42','cell43']}," +
        "{id:'5', cell:['cell51','cell52','cell53']}" +
        "]" +
        "}";  // demo data

    GetAllEmailRoles();

    function GetAllEmailRoles() {
        varType = "GET";
        varUrl = "http://localhost/restful_service_url";
        varContentType = "application/json; charset=utf-8";
        varDataType = "json";
        varProcessData = false;
        CallService();
    }

    var varType;
    var varUrl;
    var varData;
    var varContentType;
    var varDataType;
    var varProcessData;
    //Generic function to call AXMX/WCF  Service
    function CallService() {
        $.ajax({
            type: varType, //GET or POST or PUT or DELETE verb
            url: varUrl, // Location of the service
            data: varData, //Data sent to server
            contentType: varContentType, // content type sent to server
            dataType: varDataType, //Expected data format from server
            processdata: varProcessData, //True or False
            success: function(msg) {//On Successfull service call
                ServiceSucceeded(msg);
            },
            error: ServiceFailed// When Service call fails
        });
    }

    function ServiceSucceeded(result) {//When service call is sucessful

        var resultObject = null;
        if (varDataType == "json") {
            if (varUrl.indexOf(".asmx/") > 0) {
                resultObject = result.d; // Constructed object name will be object.d //Button 1
            }
            else if (varType == "GET") { resultObject = result; }

            }

            LoadDataIntoGrid(SetupJqgridJson(resultObject));
            ResetVars();
        }
    }

    function ResetVars() {
        varType = null; varUrl = null; varData = null; varContentType = null; varDataType = null; varProcessData = null;
    }
    // resultObject is from ajax success call
    function SetupJqgridJson(resultObject) {
        var cells = "";
        var total_page = 1;
        var current_page = 1;

        var id = 1;

        for (i = 0; i < resultObject.length; i++) {
            cells += "\r\n{id:'" + i + "', cell:['"
			+ resultObject[i].Name + "','"
			+ resultObject[i].Active + "','"
			+ resultObject[i].IconName + "','"
			+ resultObject[i].LastModifiedUserId + "','"
			+ resultObject[i].LastModifiedDate
			+ "']},"

        }

        var header = "{" +
				"total: '" + total_page + "'," +
				"page: '" + current_page + "'," +
				"records: '" + resultObject.length + "'," +
				"rows : [";
        var footer = "]" +
				"}";

        return header + cells + footer;
    }
    function LoadDataIntoGrid(result) {
        //alert(result);
        jQuery("#list1").jqGrid({
            datatype: "jsonstring",
            datastr: result,
            colNames: ['LastModifiedDate', 'LastModifiedUserId', 'Name', 'Active', 'IconName'],
            colModel: [{ name: 'LastModifiedDate' },
						{ name: 'LastModifiedUserId' },
						{ name: 'Name', key: true },
						{ name: 'Active' },
						{ name: 'IconName', formatter: dateFormatter },
						],
            rowNum: 10,
            rowList: [10, 20, 30],
            imgpath: gridimgpath,
            pager: jQuery('#pager1'),
            viewrecords: true,
            caption: "XML Example"
        }).navGrid('#pager1', { edit: false, add: false, del: false });
    }

    dateFormatter = function(el, cellval, opts) {
        $(el).html(formatDate(cellval));
    }

    function formatDate(vDate) {
        var d = new Date(parseInt(/\/Date\((\d+).*/.exec(vDate)[1]));
        return d.toDateString();
    }
</script>

It’s weird that formatDate() only works in version 3.4, I got uncaught exception: Syntax error, unrecognized expression: /Date(1274811887487-0600)/ error in version 3.6.

Advertisements