Datatables with strange values from json

Datatables with strange values from json

Arden54Arden54 Posts: 39Questions: 4Answers: 0

Hello,
I try to display data from my database. In my controller I return data like this : return $this->render('@gkeep/erp/view/viewArticle2.html.twig', array('data'=>$res));

$res is the json who refers to the data in my database. In my twig(html) here is the function for datatables :

`
$(document).ready(function() {
$('#example').DataTable({

              /*   "columns": [
                     {"data": 'reference'},
                     // {data: "typearticle"},
                     {"data": "designationfr"},
                     {"data": "designationen"},
                     {"data": "plan"},
                     {"data": "url"},
                     {"data": "datecreation"}
                 ],*/
                "serverSide": false,
                "bprocessing": false,
                 "dataSrc" :"",
                 "mDataProp":"",
                 //   "ajax":  "    path("viewArticle2") }}",
               "data" : "   {{ path("viewArticle2") }}",

          /*    "columnDefs":[
                    {
                        "render": function (data, type, row) {
                            return row['0'];
                       //     console.log(row);
                        },
                        "targets": 0
                    },
                    {
                        "render": function (data, type, row) {
                            return row['1'];
                        //    console.log(row);
                        },
                        "targets": 1
                    },
                    {
                        "render": function (data, type, row) {
                            return row['2'];
                       //     console.log(row);
                        },
                        "targets": 2
                    },
                    {
                        "render": function (data, type, row) {
                            return row['3'];
                            console.log(row);
                        },
                        "targets": 3
                    },
                    {
                        "render": function (data, type, row) {
                            return row['4'];
                          //  console.log(row);
                        },
                        "targets": 4
                    },
                    {
                        "render": function (data, type, row) {
                            return row['5'];
                         //   console.log(row);
                        },
                        "targets": 5
                    },
                ]*/
            });
        });

         /*    $.ajax({
                 url:  path("viewArticle2") }}',
                 type: 'GET',
                 dataType: 'json',
                 success: function (response) {
                     console.log(response)
                 }
             });*/
    </script>

`

however the data displayed in the datatables above doesn't match with the json response. And besides all data are in the first column instead of each column... Any advice or help someone, please ?

Answers

  • allanallan Posts: 61,771Questions: 1Answers: 10,112 Site admin

    Can you run the debugger on your page and let me know the debug code please?

    Also it looks like you have loaded both the DataTables and Bootstrap/DataTables stylesheets. Just load one of them. The download builder can help there.

    Allan

  • Arden54Arden54 Posts: 39Questions: 4Answers: 0

    Hi, thanks for answer !
    Here is the debug for my webpage : https://debug.datatables.net/ejixim

    Tell me if the link or the answer of your question is not good because I'm not sure of what I did.

    You are right for the stylesheets, I load 3 of them because I don't know which stylesheets I will use. I will fix it once the data in the datatables is correct.

  • Arden54Arden54 Posts: 39Questions: 4Answers: 0

    Oh, and I forgot to tell you the error message : DataTables warning: table id=example - Requested unknown parameter '1' for row 0, column 1. For more information about this error, please see http://datatables.net/tn/4

    Sorry for advance*

  • tangerinetangerine Posts: 3,350Questions: 37Answers: 394

    Did you follow the diagnostic steps at the link provided in the error message?

  • allanallan Posts: 61,771Questions: 1Answers: 10,112 Site admin

    "data": " /new_erp/web/app_dev.php/viewArticle2",

    That's not going to work. data requires an array. If you want to load data via Ajax you need to use ajax.

    The manual has more details.

    Allan

  • Arden54Arden54 Posts: 39Questions: 4Answers: 0
    edited June 2018

    Yes @tangerine, I'm trying to do my best to have it.

    Indeed @allan , that was my first step. As my json response is an array of arrays (I.E : {"data":[["article 1","des","des","plan",null,"01\/Jan\/13"]]}

    I looked into the manual : Data array location : 1) Simple array of data.
    I used the code to apply it to to my project so I have :

       $(document).ready(function() {
                     $('#example').DataTable({
                        "serverSide": false,
                        "bprocessing": false,
                        "ajax":{
                            url: " {{ path("viewArticle2") }}",
                            dataSrc: ' '
                        },
    

    Besides, I tried to add the code below but the result doesn't change.

                       "columns": [
                             {"data": 'reference'},
                             {"data": "designationfr"},
                             {"data": "designationen"},
                             {"data": "plan"},
                             {"data": "url"},
                             {"data": "datecreation"}
                         ],
    

    Am I on the good way ?

    EDIT: Updated the formatting to use the Markdown code formatting.

  • kthorngrenkthorngren Posts: 20,342Questions: 26Answers: 4,775
    edited June 2018

    Since you are using an array of arrays you don't want to use column.data as that tells Datatables to expect an array of objects.

    You will want to remove the ajax dataSrc option. Since the JSON array is return in the data object Datatables will find it by default.

    If this doesn't help please post your full Datatables init code and capture Debugger output and post the resulting link.

    Kevin

  • Arden54Arden54 Posts: 39Questions: 4Answers: 0

    Thanks for help.
    So, I follow step by step your indications but no more results. I Think that I've tried each possibilities in my function but whatever it's still not working...
    So I will post my full datatables init code and I will give you the link for the Debugger :

    Now my Datatables init code looks like this :

    <table class="display" id="example" style="width: 100%; margin-top: 10%;">
        <thead>
        <tr>
    
            <th>reference</th>
            <th>designationfr</th>
            <th>designationen</th>
            <th>plan</th>
            <th>url</th>
            <th>datecreation</th>
    
        </tr>
        </thead>
    
    
    </table>
    
    </div>
    
    
    {% endblock %}
    
        {% block javascript %}
    
           <script type="text/javascript" src=" https://code.jquery.com/jquery-3.3.1.js"></script>
            <script type="text/javascript" src="https://cdn.datatables.net/v/bs4/dt-1.10.16/b-1.5.1/datatables.min.js"></script>
            <script>
    
                     $(document).ready(function() {
                     $('#example').DataTable({
                        "serverSide": false,
                        "bprocessing": false,
                       "ajax":{
                            url: " {{  path("viewArticle2") }}"
                           // dataSrc: 'data'
                        },
            </script> 
    

    Then to load data from my database I use this function :

      /**
         * @Route("viewArticle2", name="viewArticle2")
         */
        public function listAction2()
        {
    
            $data = $this->getDoctrine()->getRepository('gkeepBundle:Article')->getAllArticle();
            //$emparray = array();
            $emparray['data'] = array();
    
            foreach ($data as $row) {
                $emparray['data'][] = [$row['reference'], $row['designationfr'], $row['designationen'],
                    $row['plan'], $row['url'], $row['datecreation']->format('d/M/y')];
            }
            $res = json_encode($emparray);
    
               return new Response($res, 200, array('Content-Type' => 'application/json'));
         //      return new JsonResponse($data, 200, array('Access-Control-Allow-Origin'=> '*'));
         // return $this->render('@gkeep/erp/view/viewArticle2.html.twig', array('data'=>$res));
        }
    

    I would like to use the Debugger but in my webpage I just have the json response. If I try to use it, it says : Content Security Policy : Parameters of the webpage has failed to load ressource from https://debug.datatables.net/bookmarklet/DT_Debug.js?rand=1529068504001 (« script-src »).

    The only way for me to have datatables on my page is to do "data" : " path("viewArticle2") }}" but it isn't the right way and it's false. I need to do it with

      "ajax":{
                            url: " {{  path("viewArticle2") }}"
                           // dataSrc: 'data'
                        },
    
    

    As conclusion I can't put the resulting link of the debugger because it doesn't work

  • Arden54Arden54 Posts: 39Questions: 4Answers: 0

    However, I can give you the link of the first option, with debogger, it is : https://debug.datatables.net/azaxiq

    thanks for advance....

  • kthorngrenkthorngren Posts: 20,342Questions: 26Answers: 4,775
    edited June 2018

    I'm confused by what you are showing as your DT init code:

            <script>
     
                     $(document).ready(function() {
                     $('#example').DataTable({
                        "serverSide": false,
                        "bprocessing": false,
                       "ajax":{
                            url: " {{  path("viewArticle2") }}"
                           // dataSrc: 'data'
                        },
                    });   //need this to close the Datatables ({
                });  //need this to close the ready function ({
            </script>
    

    And what the debugger output shows as your initialization:

    {
        "serverSide": false,
        "bprocessing": false,
        "data": " /new_erp/web/app_dev.php/viewArticle2",
        "bServerSide": false,
        "aaData": " /new_erp/web/app_dev.php/viewArticle2"
    }
    

    They don't seem to match as the debugger shows you still are using the data option.

    Also looks like you are missing }) to close the datatables and ready functions. See note above.

    Kevin

  • Arden54Arden54 Posts: 39Questions: 4Answers: 0

    Hi again, sorry for the late response time.
    Indeed I missed my copie paste and here are the new datatables function :

     <script>
    
                     $(document).ready(function() {
                     $('#example').DataTable({
                         "serverSide": false,
                         "bprocessing": false,
                        "ajax":{
                             url: "  {{  path("viewArticle2") }}",
                         }
    
                    })
                });
    </script>
    
    

    That's strange because I'm not using the data option anymore but the ajax call. Is the ajax call correct ?
    Anyway, whatever I'm using as ajax call or datatables function it doesn't work.I didn't expect that implement the datatables on my project would be that hard...

    Maybe you still have a little secret advice that I didn't use ? @allan @kthorngren

  • kthorngrenkthorngren Posts: 20,342Questions: 26Answers: 4,775

    It seems strange that the debugger output contains an old web page configuration. Have you verified the web page you are loading is correct by viewing the web page source in the browser?

    Kevin

  • Arden54Arden54 Posts: 39Questions: 4Answers: 0

    I agree with you. Yes I verified and it is correct. Still seeing the json response. No matter, I've already lost too much time by trying to implement the datatables. I will do another way to display my data ! thanks anyway for the help all !

  • allanallan Posts: 61,771Questions: 1Answers: 10,112 Site admin

    If you are able to give me a link to the page I'd be happy to check directly what is going on. The debugger shows that Ajax is not being used, so I'm not sure what is going wrong. perhaps an old cached version of the page is being used.

    Allan

This discussion has been closed.