Is there a way to get aocolumns from the server in datatable editable?
Asked Answered
M

2

17

So, I am trying to make one generic page for any table that is being requested by user. For that I am trying to fetch all data from server and not having anything hardcoded on the clientside.

 $(document).ready(function(){

     /* Add/remove class to a row when clicked on */
    $('#table1 tr').on('click', function() {
        $(this).toggleClass('row_selected');
    } );


     var which_table=window.location.pathname;
     var which_table_data=which_table.substring(0, which_table.length-1)+'/data';
     var table_name=which_table.substring(14, which_table.length-1);
     $('#table1').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "bjQueryUI": true,
            "sAjaxSource": which_table_data,
            "bPaginate": true,
            "sPaginationType": "full_numbers",
            "bjQueryUI": true,
            "sScrollX":"100%",
            "aoColumnDefs": [{
                "targets" : [0],
                "visible" : false,
                "searchable" : false
            }]
    }).makeEditable({
         "sUpdateURL": "../update/" + table_name,
         "sAddURL": "../add/" + table_name,
         "sDeleteURL": "../delete/" + table_name,
         "aoColumns": $.ajax({
                      dataType: "json",
                      url: '/get_aoColumns',
                      data: function (table_name) {
                          return {
                              q: table_name
                          };
                      },

                      results: function (data) {
                            alert(data);
                        }

                    });

    });


 });

So in this piece based on the var which_table=window.location.pathname; I try to get the data for the corresponding table from the server in which I am successful. But now I want to get even the aoColumns array from the server. My question is can I send the data in the same request along with the aoData, secho and other required fields. I think that may not render datatable properly since aoColumns in not a part of the required json. How do I get the aoColumns for any table so that even the validation becomes server side and I won`t have to design one page per table.

This below part doesnt work as I don`t know what is the correct way of doing it

"aoColumns": $.ajax({
                      dataType: "json",
                      url: '/get_aoColumns',

EDITED :-

I tried @garryp`s approach ..

This is the data I get from the server

[{"cssclass": "required", "type": "textarea"}, {"sUpdateURL": "../update/my_table", "cssclass": "required", "type": "textarea", "loadtype": "POST", "submit": "OK"}, {"loadurl": "../data/", "sUpdateURL": "../update/my_table", "loadtype": "POST", "type": "select", "submit": "OK"}]

This is my code :

 $(document).ready(function(){

     /* Add/remove class to a row when clicked on */
    $('#table1 tr').on('click', function() {
        $(this).toggleClass('row_selected');
    } );



     var which_table=window.location.pathname;
     var which_table_data=which_table.substring(0, which_table.length-1)+'/data';
     var table_name=which_table.substring(14, which_table.length-1);
     if(table_name.indexOf('Welog')> -1) {
         $('#table1').dataTable({
             "bProcessing": true,
             "bServerSide": true,
             "bjQueryUI": true,
             "sAjaxSource": which_table_data,
             "bPaginate": true,
             "sPaginationType": "full_numbers",
             "bjQueryUI": true,
             "sScrollX": "100%"
             });
           $('#formAddNewRow').hide();


        }
     else {
         $.ajax({
             url: '../get_aodata/' + table_name,
             async: false,
             success: function (data) {
                 alert(data);
                 $('#table1').dataTable({
                     "bProcessing": true,
                     "bServerSide": true,
                     "bjQueryUI": true,
                     "sAjaxSource": which_table_data,
                     "bPaginate": true,
                     "sPaginationType": "full_numbers",
                     "bjQueryUI": true,
                     "sScrollX": "100%",
                     "aoColumnDefs": [{
                         "targets": [0],
                         "visible": false,
                         "searchable": false
                     }]
                 }).makeEditable({
                     "sUpdateURL": "../update/" + table_name,
                     "sAddURL": "../add/" + table_name,
                     "sDeleteURL": "../delete/" + table_name,
                     "sAddDeleteToolbarSelector": "#table1_length",
                     "aoColumns" : data

             /*"aoColumns" : [
                         {
                             "cssclass": "required",
                             "type":"textarea"
                         },
                         {
                             "cssclass": "required",
                             "type":"textarea",
                             "submit"  : "OK",
                             "sUpdateURL": "../update/"+table_name,
                             "loadtype" : "POST"
                         },
                         {
                             "loadurl" : "../data/",
                             "type" : "select",
                             "submit": "OK",
                             "sUpdateURL": "../update/"+table_name,
                             "loadtype" : "POST"
                         }
                     ]*/

                 });
             }
         });
     }

 });

So if you see the commented out aoColumns in this code is exactly the same as the output got from the server, but the one got from the server doesnt work and the one commented out if uncommented does work. The one got from the server if used using aoColumns : data just behaves the same way as if aoColumns parameter wasnt mentioned at all in the makeditable function. Does that mean data is not reaching that parameter coz I don`t get any errors in the console.

Solution :-

success : function(data){
  var data_str= JSON.parse(data);
});

Ok. I had to convert the json string to JSobject using parse and then it finally worked.

Misread answered 8/5, 2015 at 5:22 Comment(0)
L
6

It doesn't work because you are assigning the return value of $.ajax(...) to aoColumns here (when you actually need to be assigning an array of columns to "aoColumns"):

}).makeEditable({

     ...

     "aoColumns": $.ajax({

Instead what you need to do is make the AJAX call FIRST. Then, inside the jQuery success function setup your datatable.

$.ajax({
    url: '/get_aoColumns',
    ...
    success : function(data) {
        // ToDo: put all your datatable code in here.
        // and assign `data` to "aoColumns"

            /** data table code **/

        }).makeEditable({
        "aoColumns": data

            /** rest of data table code **/
    }

I have tried to leave all but the important bits out to make the key points clear, but this should help you understand where you have gone wrong.

I've set up a JS Fiddle here with an (untested) code sample if this doesn't make sense:

http://jsfiddle.net/GarryPas/got4fxhb/1/

Lanford answered 10/5, 2015 at 22:7 Comment(3)
Got the gist. Let me try it. I was researching about the same.Misread
OK I added a JS fiddle too in case there was confusion.Lanford
Hi, sorry I haven't been following the thread. I notice you edited a couple of hours ago. Does this mean you've got your code working now?Lanford
S
-1

assuming /get_aoColumns is returning everything correctly, it looks like you want to fetch that information first, and then in the success handler, create the datatable. In your code above, it looks like the dataTables declaration can finish before the ajax request has a chance to complete, so how about this:

$(document).ready(function () {
    /* Add/remove class to a row when clicked on */
    $('#table1 tr').on('click', function () {
        $(this).toggleClass('row_selected');
    });
    var which_table = window.location.pathname;
    var which_table_data = which_table.substring(0, which_table.length - 1) + '/data';
    var table_name = which_table.substring(14, which_table.length - 1);

    //wrap the ajax request to get aoColumns outside of the initializaer
    $.get('/get_aoColumns', {q: table_name}, function (aoColumns) {
        $('#table1').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "bjQueryUI": true,
            "sAjaxSource": which_table_data,
            "bPaginate": true,
            "sPaginationType": "full_numbers",
            "sScrollX": "100%",
            "aoColumnDefs": [{
                    "targets": [0],
                    "visible": false,
                    "searchable": false
                }]
        }).makeEditable({
            "sUpdateURL": "../update/" + table_name,
            "sAddURL": "../add/" + table_name,
            "sDeleteURL": "../delete/" + table_name,
            "aoColumns": aoColumns //the data retrieved from the request to get_aoColumns
        });
    });
});
Sungod answered 10/5, 2015 at 22:15 Comment(2)
ha, thanks, yeah I figured it wasn't you, I was asking "the silent anonymous downvoter". Did this do anything for you? I'm guessing noSungod
No. This approach didn`t work. Can u see my updated question and suggest what is wrong. @SungodMisread

© 2022 - 2024 — McMap. All rights reserved.