How to use DataTable ajax to get json data from jsp page by sending parameter?

How to use DataTable ajax to get json data from jsp page by sending parameter?

miteshjoshimiteshjoshi Posts: 8Questions: 2Answers: 0
edited July 2019 in Free community support

Hi,
I want to make two HTML tables on same page. The first table is made successfully by calling DataTable instance $(#selector).DataTable() once for the table. Now on click event for each select button on the first column of this table, I want to make second table at its bottom, which takes some column values for each row clicked, passes it to the jsp page (where servlet functions are written), get back the data in json format and construct the table accordingly. the table has to be refreshed for every set of data sent with each row-click event. I tried all sort of method but unable to do so. I am sharing what I have done till now !
() [](https://datatables.net/forums/uploads/editor/q1/1nwjgbd16rze.txt ""). ()

As can be seen in the main JSP page, I have used all the combination of DataTable I could understand. Pls help me out.

This question has accepted answers - jump to:

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @miteshjoshi ,

    Probably the easiest way would be something like this: http://live.datatables.net/dabotiri/1/edit

    The second table is present, but hidden, and once the main table is clicked upon, it triggers a load of the second table.

    Hope that helps,

    Cheers,

    Colin

  • miteshjoshimiteshjoshi Posts: 8Questions: 2Answers: 0

    Hi Colin,
    Thanks for the prompt response. But the design suggested by you helps me partially. My main problem lies in getting the JSON data from scriptlet written on the page "asydetail.jsp" where I have used GSON library to convert it to JSON format. Will the 'url' parameter of Datatable ajax take the name of jsp page or the property name of json returned?.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @miteshjoshi ,

    I'm not familiar with that server end. I'd expect your jsp scriptlet to either parse the URL, or if it doesn't, you could use ajax.data to send the property.

    Cheers,

    Colin

  • miteshjoshimiteshjoshi Posts: 8Questions: 2Answers: 0
    edited July 2019

    Tried by failed with ajax.data. The response obtained from asydetail.jsp is
    **returnJSON is {"asyrecords":[{"slno":2,"asydrgno":"01393701005","asyvar":"00","itemno":15,"qty":4,"wunit":"NO","desc1":"GASKET","noff":2.0},{"slno":3,"asydrgno":"01393701005","asyvar":"00","itemno":14,"qty":2,"wunit":"NO","desc1":"GASKET","noff":1.0},{"slno":4,"as
    **
    The piece of script used by me is for fetching this json by datatable ajax is;

    **var oTable = $('#assydetail').dataTable({
                         "processing": true,
                         "serverSide": true,
                         "ajax": {
                            "url": "asydetail.jsp",
                            "dataSrc": "asyrecords",
                            "dataType": "json",
                            //"data": {lastno:lastno,lastyr:lastyr,prod:prod},
                            "type": "GET",
                            "columns": [
                               {"data": "asydrgno"},
                                {"data": "asyvar"},
                                {"data": "itemno"},
                                {"data": "qty"},
                                {"data": "wunit"},
                                {"data": "asyvar"},
                                {"data": "desc1"},
                                {"data": "noff"}
                             ]
                   
                         }
    

    Is anything wrong with my ajax configuration? Will datatable ajax, like jQuery, get the requied json on-the-fly OR do I need to save this JSON first in file and then read it?

    Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    You've got the columns within the ajax block - try moving it out to the top-level. It will get the JSON on the fly, and just replace what's already in the table with the new data. The JSON response looks valid to me, is there something wrong with it?

  • miteshjoshimiteshjoshi Posts: 8Questions: 2Answers: 0

    Thanks Colin.
    The error was in the column attribute. Once outside the Ajax, it worked fine. By the way, can you suggest solution to one more problem.
    I want to add one more column having the select button in each row as the first column of the table. I have created a <thead> for this.
    In normal jQuery, I use to create a new DOM element <td> and <tr> inside jQuery success block and append it to HTML separately before iterating thru the JSON object with each loop (and adding it to subsequent columns of each row).
    Now since here, DataTable() instance is creating the table for me, how can I add this extra column.
    Taking much of your time, but in absence of any internet stuff regarding DataTable, have to ask it in this forum. Hope you don't mind.

    Regards,
    Mitesh

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
  • miteshjoshimiteshjoshi Posts: 8Questions: 2Answers: 0

    Yes Colin. I mean the same but I am not using select extension. Instead I am using columnDefs.render for the same as can be seen below:

     $('#updlst').DataTable({
                                    "columnDefs": [{"orderable": false, "searchable": false, "targets": 0, 
                                                    "render": function(data, type, full, meta)
                                                    {return '<input type="radio" name="id" value="">';}
                                                    }],
                                     "order": [[ 1, 'asc' ]],           
                                     //fixedColumns: {heightMatch: 'none'}
                                });   
    

    I was expecting to get the radio button in the first column of each row but was getting it in the first row only with the loss of first column data for that row. In subsequent rows, data has started rendering from the first column itself instead of the expected second column. Have a snapshot of this

    Second query is that when using serverside processing of DataTable, do I need to return extra parameters from my JSON data, as the data returned to me from my earlier attempts, mentioned above, is not getting paginated or sorted.

    With Regards,
    Mitesh

  • kthorngrenkthorngren Posts: 21,349Questions: 26Answers: 4,955
    Answer ✓

    Sounds like you might be getting a Javascript error. Check the browser's console for errors. Are you getting any?

    Kevin

  • miteshjoshimiteshjoshi Posts: 8Questions: 2Answers: 0

    Yes Kevin. I reached the error point. Silly mistake. My <thead> was not matching the <tbody> data columns.
    However, If I use two-tables in a page in master-slave fashion with the master table providing data for the slave scripting, I am not able to refresh the slave table with the same formatting as in the first instance, whenever data is refreshed.
    Here, I would like you to know that I am NOT using the server-side scripting. My DataTable is getting data from the HTML table itself. The Master table is rendering perfectly. But since for each set of data from my master table individual row, the slave data (in json format obtained by jQuery ajax) is getting refreshed, I am not able to refresh the DataTable format (e.g. pagination, centering etc) in each refresh on data-loading. However, it regains these format, once I click on the sort icon of any column. Why so? Showing you the snapshot
    here is my code

     $.each(data.asyrecords, function(i){
                                     var tbody = $('#assydetail tbody');
                                     var tr = $('<tr>');
                                     $('<td>').html("<input type = 'radio' name = 'detSelect' class = 'detSelect'/>").appendTo(tr);
                                     $.each(this, function(key,value){
                                         $('<td>').text(value).appendTo(tr);
                                     });//end of inner each
                                     tbody.append(tr); 
                                 });//end of outer each
                                 
                         **    if ( ! $.fn.DataTable.isDataTable('#assydetail'))
                             { 
                                var dtTable = $('#assydetail').DataTable({
                                      //"destroy": true, 
                                      "processing": true,
                                      "columnDefs": [{"className": "dt-center", "targets": "_all"},
                                                    {"orderable": false, "searchable": false, "targets": 0}],
                                      "order": [[ 1, 'asc' ]],          
                                      "fixedColumns":{heightMatch: 'none'}
                                  });
                             }
                             else
                             {    
                                  dtTable.destroy();
                                   //dtTable.ajax.reload(null, false);    **
                             }  
                              },//end of success block
                            error: function (xhr, ajaxOptions, thrownError) {
    

    Can you suggest the way out?

    Regards,
    Mitesh

  • miteshjoshimiteshjoshi Posts: 8Questions: 2Answers: 0

    Any solution friends for my above problem. I am still not able to redrawn the same datatable in the second attempt with fresh data. I have tried the options table.ajax.reload(), table.clear().draw(), table.destroy() etc options available over datatable forum but in vain. Any other option available?
    Here I want to once again mention that I am not using DataTable.ajax option to fetch the json but** jQuery.ajax option** to get data. Thereafter I am inserting DOM elements by jQuery once-by-one, constructing a normal HTML table and then** instantiating the** Datatable() for that HTML table. Since 2nd table is getting data based on the records in the 1st table, it has to be redrawn time and again.
    Hope I have made my point clear. Will be more than happy for any timely solution.

    Regards,
    Mitesh

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @miteshjoshi ,

    There's a lot going on here - could you create a test case or link to your page, please. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

This discussion has been closed.