jQuery UI Widgets Forums Grid jqwidgets Grid with JSP Servlet server side

Tagged: , , ,

This topic contains 11 replies, has 4 voices, and was last updated by  Akshatha Raju 11 years, 4 months ago.

Viewing 11 posts - 1 through 11 (of 11 total)
  • Author

  • mail2harisha
    Member

    Hi All,

    I am trying to use jqwidgets Grid with JSP servlet to get server side data and display in client side. But I am getting JSON Parse error. Below is my sample program:

    Main jsp (json.jsp)

    Grid populated from JSON.

    $(document).ready(function () {
    var url = "getdata.jsp";

    alert("url ["+url+"]");
    // prepare the data
    var source =
    {
    datatype: "json",
    datafields: [
    { name: 'name' },
    { name: 'type' },
    { name: 'calories' },
    { name: 'totalfat' },
    { name: 'protein' },
    ],
    id: 'id',
    url: url
    };
    alert("source="+source);
    var dataAdapter = new $.jqx.dataAdapter(source, {
    downloadComplete: function (data, status, xhr) { alert("downloadComplete"); },
    loadComplete: function (data) { alert("loadComplete"); },
    loadError: function (xhr, status, error) {
    alert("error occured");
    alert("xhr ["+xhr+"] status ["+status+"] error ["+error+"] ");
    }
    });
    $("#jqxgrid").jqxGrid(
    {
    width: 670,
    source: dataAdapter,
    columns: [
    { text: 'Name', datafield: 'name', width: 250 },
    { text: 'Beverage Type', datafield: 'type', width: 250 },
    { text: 'Calories', datafield: 'calories', width: 180 },
    { text: 'Total Fat', datafield: 'totalfat', width: 120 },
    { text: 'Protein', datafield: 'protein', width: 120 }
    ]
    });
    });

    getdata.jsp (which is in same location as json.jsp)

    Helper class

    package com.pack;

    import net.sf.json.JSONObject;

    public class Helper {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method s
    System.out.println(new Helper().getData());
    }

    public JSONObject getData() {
    log.debug("Enter getData]");
    JSONObject object = null;
    try {
    object = new JSONObject();
    object.put("id", "1");
    object.put("name", "Super Chilli Hot Chocolate");
    object.put("type", "Chocolate Beverage");
    object.put("calories", "20");
    object.put("totalfat", "16g");
    object.put("protein", "14g");

    log.info("Return data is [" + object.toString() + "]");
    } catch (Exception e) {
    log.error("Error occurred", e);
    e.printStackTrace();
    }
    log.debug("Exit getData]");
    return object;
    }
    }

    here are my question:
    1. Does jqwidgets supports Java JSP servlet (as no where it is mentioned in website)?
    2. getdata.jsp seems not to be called
    3. Is anything missing?
    4. Is this is the correct JSON package net.sf.json.JSONObject?

    Kindly help.


    mail2harisha
    Member

    Updated the content

    getdata.jsp (which is in same location as json.jsp)

    out.print(new Helper().getData());
    out.flush();


    Peter Stoev
    Keymaster

    1. Could you post the results of the call of your getData() function?
    2. Did you try to make a call to the “getdata.jsp” using the jQuery’s ajax function? If yes, can you post here the results of the data object in the success function.

    Looking forward to your reply.

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com


    mail2harisha
    Member

    Hi Peter,

    Thanks for your reply. below are the answers to your question:

    1. Could you post the results of the call of your getData() function?

    {“id”:”1″,”name”:”Super Chilli Hot Chocolate”,”type”:”Chocolate Beverage”,”calories”:”20″,”totalfat”:”16g”,”protein”:”14g”}

    I tried to hard code the return value to below, but that also resultant in same JSON parse error.
    [{“id”:”1″,”name”:”Super Chilli Hot Chocolate”,”type”:”Chocolate Beverage”,”calories”:”20″,”totalfat”:”16g”,”protein”:”14g”}]

    2. Did you try to make a call to the “getdata.jsp” using the jQuery’s ajax function? If yes, can you post here the results of the data object in the success function.

    The result is:
    {“id”:”1″,”name”:”Super Chilli Hot Chocolate”,”type”:”Chocolate Beverage”,”calories”:”20″,”totalfat”:”16g”,”protein”:”14g”}

    I slightly changed the program:
    Sample program is:
    $(function() {
    $("#button").click(function() {
    alert("hi");
    $.ajax( {
    type: "GET", // the default
    url: "GetPerson", //servlet name
    data: { id: $("#sel").val() },
    success: function(data) {
    alert("success");
    alert(data);
    $("#out").html( data );
    }
    } );

    });
    });

    Servlet
    package servlet;

    import java.io.*;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;

    import net.sf.json.JSONObject;

    import models.People;

    public class GetPerson extends HttpServlet {

    /**
    *
    */
    private static final long serialVersionUID = 1L;
    private People people = new People();

    protected void doGet(
    HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
    // String id = request.getParameter("id");
    // out.print(people.getPerson(Integer.parseInt(id)));
    JSONObject object = null;

    object = new JSONObject();
    object.put("id", "1");
    object.put("name", "Super Chilli Hot Chocolate");
    object.put("type", "Chocolate Beverage");
    object.put("calories", "20");
    object.put("totalfat", "16g");
    object.put("protein", "14g");
    out.print(object.toString());

    } finally {
    out.close();
    }
    }

    }

    This above program when called through jquery + ajax it is giving aove result, but when i try with jqwidgets it is still giving JSON parser error.

    Please note: we are doing POC for our company, if it gets succesfull we may buy this framework. So, kindly help.


    Peter Stoev
    Keymaster

    The following code uses the data returned from your getData() function and loads the Grid.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
    <script type="text/javascript" src="../../scripts/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxscrollbar.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxmenu.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.columnsresize.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxlistbox.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxdropdownlist.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
    $(document).ready(function () {
    var dataResult = '[{"id":"1","name":"Super Chilli Hot Chocolate","type":"Chocolate Beverage","calories":"20","totalfat":"16g","protein":"14g"}]';
    // prepare the data
    var source =
    {
    datatype: "json",
    datafields: [
    { name: 'name' },
    { name: 'type' },
    { name: 'calories' },
    { name: 'totalfat' },
    { name: 'protein' },
    ],
    id: 'id',
    localdata: dataResult
    };
    var dataAdapter = new $.jqx.dataAdapter(source);
    $("#jqxgrid").jqxGrid(
    {
    width: 670,
    source: dataAdapter,
    columns: [
    { text: 'Name', datafield: 'name', width: 250 },
    { text: 'Beverage Type', datafield: 'type', width: 250 },
    { text: 'Calories', datafield: 'calories', width: 180 },
    { text: 'Total Fat', datafield: 'totalfat', width: 120 },
    { text: 'Protein', datafield: 'protein', width: 120 }
    ]
    });
    });
    });
    </script>
    </head>
    <body class='default'>
    <div id='jqxWidget'>
    <div id="jqxgrid"></div>
    </div>
    </body>
    </html>

    Hope this helps.

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com


    mail2harisha
    Member

    Hi peter,

    I have tried this, it works. But the problem is getting the same data(same format) from server side(jsp or servlet) and displaying the grid in client side. There i am getting JSON parse error.

    Can somebody please send me a sample grid program which gets data in JSON(or other format) from jsp or servlet?


    Peter Stoev
    Keymaster

    Hi mail2harisha,

    Isn’t it possible to edit your getData function and return this [” + object.toString() + “]” instead of ‘object’?

    The other approach is as your data comes as: {“id”:”1″,”name”:”Super Chilli Hot Chocolate”,”type”:”Chocolate Beverage”,”calories”:”20″,”totalfat”:”16g”,”protein”:”14g”}, do this:

            var dataAdapter = new $.jqx.dataAdapter(source,
    {
    downloadComplete: function (data) {
    return $.makeArray(data);
    }
    }
    );

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com


    mail2harisha
    Member

    Hi peter,

    Thanks a lot for your reply. Its working now 🙂

    Isn’t it possible to edit your getData function and return this [” + object.toString() + “]” instead of ‘object’?

    I had tried both option then also it was not working

    The other approach is as your data comes as: {“id”:”1″,”name”:”Super Chilli Hot Chocolate”,”type”:”Chocolate Beverage”,”calories”:”20″,”totalfat”:”16g”,”protein”:”14g”}, do this:

    var dataAdapter = new $.jqx.dataAdapter(source,
    {
    downloadComplete: function (data) {
    return $.makeArray(data);
    }
    }
    );

    By doing this, it is working. Thank you very much.

    Can I know the difference between this option and earlier one?

    Also, one suggestion would be please add some sample program of jqwidgets using Java JSP and servlets.


    ssp
    Participant

    Hi,

    I am referring to your Nested Grid sample code, which works when I test your sample code using xml data,

    but in my case, I am using JSON data and am able to get the resultsets for both the  parent and the child  grids( found on debugging),  but only the parent grid data is displayed and nested grid is displayed blank( without grid),

    It is not linking with the second URL(  url: ‘getSecondGridForRevisionHistory.htm’  ), thus displaying only the parent grid…

    What should be the main criteria to link the child grid with the parent grid?

    Should there be a common ID field in both the grids? please explain!!

    $(document).ready(function () {
    var theme = getDemoTheme();
    var sourceFirstGrid =
    {
    datatype: “json”,
    datafields: [
    { name: ‘leadProjectNumber’ },
    { name: ‘projectNumber’ },
    { name: ‘pdxType’ }

    ],
      id: ‘projectNumber’,
    cache: false,
    url: ‘getFirstGridForRevisionHistory.htm’
    //     url:’getSummaryGridData.htm’
    };

    var firstGridAdapter = new $.jqx.dataAdapter(sourceFirstGrid);
    var sourceSecondGrid =
    {
    datatype: “json”,
    datafields: [
    //  { name: ‘projectNumber’ },
    { name: ‘modifiedDate’ },
    { name: ‘modifiedBy’ },
    { name: ‘projectNumber’ },
    { name: ‘leadProjectNumber’ },
    { name: ‘status’ },
    { name: ‘checkinComments’ },
    { name: ‘remarks’ }
    ],

    cache: false,
       url: ‘getSecondGridForRevisionHistory.htm’
    };
    var secondGridAdapter = new $.jqx.dataAdapter(sourceSecondGrid);

     

    Thanks & Regards,

    Sandhya S P


    ssp
    Participant

    Hi,
    After using your sample code for JSON data now I am able to link into the URL of the nested grid!

    but I am not able to display the values in the grid other than the column names of both the grid..
    I able to implement everything from your sample php code in my java except the below lines:-

    beforeprocessing: function (data) {
    source.totalrecords = data[0].TotalRows;
    },

    I am returning the entire JSON data as “return strJsonRevisionHistoryGrid” from the controller which contains the below data,
    strJsonRevisionHistoryGrid:{“firstGridForHistory”:[{“projectRevisionId”:0,”projectNumber”:”04.45555″,”location”:null,”statusId”:0,”status”:null,”jobId”:0,”jobCodeId”:0,”jobName”:null,”jobCodeName”:null,”hours”:0.0,”hoursDifference”:0.0,”total”:0.0,”author”:null,”modifiedDate”:null,”costDiff”:0.0,”modifiedBy”:null,”leadProjectNumber”:”04.45555″,”checkinComments”:null,”crNumber”:null,”pdxType”:”PD2″,”remarks”:null},

    Please explain if data[0].TotalRows is the reason for the data being not displayed in the grid and how should I modify the below in my case:
    beforeprocessing: function (data) {
    source.totalrecords = data[0].TotalRows;
    },

    Thanks & Regards,

    Sandhya S P


    ssp
    Participant

    I am referring to your sample code “server_side_grid__with_nested_grids” in phpdemos,

    data[] and TotalRows are defined in “data file” of your code,

    but my query is how r they linked/defined in the “index file”??

    please explain, as this may be the reason I am unable to display data in both the grids

    because even though I am able display the data in the console

    strJsonRevisionHistoryGrid:{“firstGridForHistory”:[{“projectRevisionId”:0,”projectNumber”:”04.45555″,”location”:null,”statusId”:0,”status”:null,”jobId”:0,”jobCodeId”:0,”jobName”:null,”jobCodeName”:null,”hours”:0.0,”hoursDifference”:0.0,”total”:0.0,”author”:null,”modifiedDate”:null,”costDiff”:0.0,”modifiedBy”:null,”leadProjectNumber”:”04.45555″,”checkinComments”:null,”crNumber”:null,”pdxType”:”PD2″,”remarks”:null},

    strJsonRevisionHistoryGrid:{“firstGridForHistory”:null,”secondGridForHistory”:[{“projectRevisionId”:0,”projectNumber”:”04.11111″,”location”:null,”statusId”:0,”status”:”Proposal”,”jobId”:0,”jobCodeId”:0,”jobName”:null,”jobCodeName”:null,”hours”:0.0,”hoursDifference”:0.0,”total”:0.0,”author”:null,”modifiedDate”:”18-JUL-2013 02:49 PM”,”costDiff”:0.0,”modifiedBy”:”Madhu Kumar KS”,”leadProjectNumber”:”04.11111″,”checkinComments”:”Distributed from GPDX”,”crNumber”:null,”pdxType”:null,”remarks”:”-“},

Viewing 11 posts - 1 through 11 (of 11 total)

You must be logged in to reply to this topic.