1

(Message updated according to the help I got in the meantime)

I'm trying to get my jQuery dataTable to be populated dynamically via Ajax (both th's and td's).

To do so, I'm religiously following a jsfiddle script that I found around here and that seems to work.

The difference is that the person who wrote this script just hardcoded his "dataSet" variable prior to using it while I need to generate it automatically from php and then parse it in jQuery.

When I try to do so, all I get is:

TypeError: e is not an Object. (evaluating '"length"in e').

Islam helped me a great deal by chat in the meantime and it seems that the formatting and console.log(dataSet) are now ok.

Here is my (updated) attempt:

HTML:

<table id="example"></table> 

PHP:

<?php
    $dataset=array();
    ....
    while($row = mysqli_fetch_assoc($sql)) {
        .....
        $array_tmp = array();
        $array_tmp["Header1"] = $alias;
        $array_tmp["Header2"] = $chambres;
        $array_tmp["Header3"] = $adresse;
        $dataset[] = $array_tmp;
    }
    ....
    echo json_encode($dataset, JSON_UNESCAPED_UNICODE);
?>

jQuery:

var my_columns = [];
var dataSet =[];

$.ajax({
    type: "GET",
    url:  "myfile.php",
    data: 'value=1',
    datatype:'json',
    cache: false,
    success: function(response){
        dataSet=response;
        $.each( dataSet[0], function( key, value ) {
            var my_item = {};
            my_item.data = key;
            my_item.title = key;
            my_columns.push(my_item);
        });
    }
});

islam jsFiddled the code with some of my production data and it works but I still get the error message on my side. So, it's really a mystery.

What I show you here is exactly what I have. So there is nothing else different that is changing the game.

I use the same jQuery and dataTables than in the islam jsFiddled. Both are set and working as I use dataTables successfully except for this specific attempt of retrieving server data. I use no other library.

when I "console.log(dataSet)" on my side, here is what I get (which seems to be fine):

[
    {
        "Header1" : "tyurtyu",
        "Header2" : "zertzert",
        "Header3" : 123
    },
    {
        "Header1" : "sdfsdfsd" ,
        "Header2" : "dsfgsdfg",
        "Header3" : 456
    }
]

FYI, here is the commented call to dataTables that I don't use yet because I get the error message on the Ajax call already. At least, it'll show where my dataSet array is supposed to be used afterwards.

/*
var dataTable = $('#example').DataTable({
    'bInfo'  : false,
    'paging' : false,
    'scrollX': false,
    'processing':false,
    'sDom'   : 'ltipr',
    'data'   : dataSet,
    "columns": my_columns
});
*/

If I uncomment this call to the dataTable, I get another error message on top of the other:

TypeError: e is not an Object. (evaluating '"length"in e')
TypeError: undefined is not an object (evaluating 'e[i].aDataSort')

Any help would be appreciated.

UPDATE: I got rid of the first error message by changing the way I pass from "response" to "dataSet", like this:

    success: function(response){

        dataSet = JSON.parse(response);
        //instead of "dataSet=response;"

        $.each(dataSet[0], function(key, value) {
            ...
        });
    }

So now, I only have the second error message when trying to pass dataSet to the dataTable.

It seems that it's just a scope issue as console.log(dataSet) outside the ajax call, like here below won't output anything

var my_columns = [];
var dataSet =[];

$.ajax({
    type: "GET",
    url:  "php/ajax/get_table_values.php",
    data: 'value1=1',
    datatype:'json',
    cache: false,
    success: function(response){
        dataSet = JSON.parse(response);
        //instead of "dataSet=response;"

        $.each(dataSet[0], function(key, value) {
            var my_item = {};
            my_item.data = key;
            my_item.title = key;
            my_columns.push(my_item);
        });
    }
});

console.log(dataSet);

var dataTable = $('#example').DataTable({
    'bInfo'  : false,
    'paging' : false,
    'scrollX': false,
    'processing':false,
    'sDom'   : 'ltipr',
    'data'   : dataSet,
    "columns": my_columns
});

UPDATE: problem solved, see my other post below. Thank you all!

4
  • 1
    set dataType: "json", in ajax. Commented Feb 15, 2019 at 9:23
  • I did that but it didn't work. It just outputs more backslashes within the array but the error messages are exactly the same. And dataSet[0] is exactly what is in the jsfiddle example but it works and outputs all the values. Commented Feb 15, 2019 at 9:25
  • have you added datatable js files? Commented Feb 15, 2019 at 9:26
  • yes. DataTables works for everything else but this. Commented Feb 15, 2019 at 9:27

6 Answers 6

2

on your php file do something like this:

 if ($_POST["action"] == "SLC" && isset($_POST["categoryId"])) {
         $category= $_POST["categoryId"];
         //do your query here btw use PDO is better
         //fill your data here and then return it
         $result = $command->fetchAll(PDO::FETCH_ASSOC)
         $return["data"] = $result;
         echo json_encode($return,JSON_UNESCAPED_UNICODE);
    }

then in your javascript call it like this:

var tableTypeOfClientInfo = $('#tableTypeOfClientInfo ').DataTable({
                       "destroy": true,
                       "responsive":{
                         "details": {
                         renderer: function ( api, rowIdx, columns ) {
                           var data = $.map( columns, function ( col, i ) {
                             return col.hidden ?
                               '<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
                                 '<td>'+col.title+':'+'</td> '+
                                 '<td>'+col.data+'</td>'+
                               '</tr>' :
                               '';
                           } ).join('');

                           return data ?$('<table/>').append( data ) :false;
                         }
                       }
                     },
                       "autoWidth": false,
                             "ajax": {
                                 "url": 'some.php',
                                 "method": 'POST',
                                 data:{action:"SLC", categoryId:id}
                             },
                             "columns": [
                                 {"data": "identification_number"},
                                 {"data": "address"},
                                 {"data": "birthday"},
                                 {"data": "phone"},
                                 {"data": "mail"}
                             ],
                             "language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
                               "columnDefs": [
                                 {
                                   "className": "dt-center", "targets": "_all"
                                  }
                               ]
                         });
Sign up to request clarification or add additional context in comments.

4 Comments

Hi and thank you for your help. As I posted recently, my problem is solved. However, does your script add anything useful that I should consider to improve mine?
@BachirMessaouri yeah if youa dd the datatable script for responsive stuff it handle the rows in the responsive method also it fill the datatable with the datatable method using ajax too
Ok thanks. But then how would you improve it to fetch the headers dynamically (that's the point of my script but yours doesn't address this point, which is important to me)? I see here that you have to hardcode your columns names.
@BachirMessaouri in my example you need to have a predifined div with the header names what you can do in that case is put the datatable call inside a click event then the segment data is an array wich you can obtain from your php and load it into your div with the heads names
1

You'd need not to create a string, but an array with the correct format :

$dataset=array();
...
while($row = mysqli_fetch_assoc($sql)) {
    ....
    $array_tmp = array();
    $array_tmp["Header1"] = $string_val1;
    $array_tmp["Header2"] = $string_val1;
    $array_tmp["Header3"] = $numval3;

    $dataset[] = $array_tmp;
}

7 Comments

That's the thing. How to get the correct format? I suspect it's a format problem but in the end, I'm stuck because I don't know how to get that format. At least, with a string chain, I can get what I've got. Beyond that, I don't have a clue.
@BachirMessaouri did you check my code? I kinda gave you an idea how to get the correct format :-)
Yes. If I do exactly that and echo $dataset (without changing anything in jQuery), then I get the exact same error messages. Thank you for your help.
Could you console.log(dataset) and console.log(my_columns) ?
|
1
<?php

 $dataset='';
 ...
while($row = mysqli_fetch_assoc($sql)) {
 ....
  $dataset[]=array(
     "Header1" : $string_val1,
     "Header2" : $string_val1,
     "Header3" : $string_val1
  );
}
...

echo json_encode($dataset);

use $dataset as array and just echo the json encoded array to get json object in the script

10 Comments

try changing dataSet[0] to dataSet in $ each
$.each(dataSet[0], function(key, value) { var my_item = {}; my_item.data = key; my_item.title = key; my_columns.push(my_item); }); console.log(my_columns) $(document).ready(function() { $('#example').DataTable({ data: dataSet, "columns": my_columns }); }); try this and check console for what is in my_columns
I got it to output my_columns eventually! I changed dataset=response with dataSet = JSON.parse(response). So my first error message is gone. Still remains the second one when trying to call dataTables. TypeError: undefined is not an object (evaluating 'e[i].aDataSort') But it's a huge step forward.
I updated the original message (see second part of it). I think it's just a variable scope issue this time (getting dataSet outside of the Ajax call).
then move the loop outside the ajax call
|
1

Problem solved!

Ok, I eventually got it to work, with the valuable help of islam and the guidance of Shafeeque TP. All the people who posted helped me a lot. Thank you all.

First, the PHP had to be right:

<?php
    $dataset=array();
    ....
    while($row = mysqli_fetch_assoc($sql)) {
        .....
        $array_tmp = array();
        $array_tmp["Header1"] = $alias;
        $array_tmp["Header2"] = $chambres;
        $array_tmp["Header3"] = $adresse;
        $dataset[] = $array_tmp;
    }
    ....
    echo json_encode($dataset, JSON_UNESCAPED_UNICODE);
?>

This formatted the dataSet array as it should.

Then, the data passed from response to dataSet in the jQuery ajax call had to be made right:

success: function(response){

    dataSet = JSON.parse(response);
    //instead of "dataSet=response;"

    $.each(dataSet[0], function(key, value) {
        ...
    });
}

Now the first error message disappeared.

And then I had to access the dataSet and my_columns arrays outside the Ajax call:

var my_columns = [];
var dataSet =[];

$.ajax({
    ...
    async: false,
    ...
    success: function(response){
        ...
    }
}); 

And now, it works. The two working jsfiddle's in the original question didn't help precisely because they contained no array to be converted and that was the problem. Thankfully, I got there eventually.

Thank all of you for your guidance. Very much appreciated!

Comments

0

I followed these steps:

1 - Create the ajax:

function getDataTest(attribute_ajax_id) {
  $.ajax({
    url:  "{{ route('datatable_data_list') }}" ,
    type: 'POST',
    data: {
      attribute_ajax_id: attribute_ajax_id,
      "_token": "{{ csrf_token() }}"
    },
    success: function(response){
      for(let i =0; i < response.length; i++) {
        console.log(response[i]['column_one_id'])              
      }
    } 
  });
}

2 - Create backend return with custom array:

$customArray = [];
$modelData = TestModel::where('column_id', $request->attribute_ajax_id)->get();

foreach($modelData as $row) {
   $customArray[] = [
    'column_one_id' => $row->column_one_id,
    'column_two_id' => $row->column_two_id,
    'test' => $row->relationship->column_relationship
  ];
}

return Datatables($customArray)->make(true);

Comments

-1

You use$.each it need a object. Try in you php file change$dataset = json_encode($dataset);

And I think $dataset must be a array

And this

 $dataset=json_encode($dataset, Json_force_object); 

And try code from Islam i think it is right code, enter

<?php

 $dataset=array();
 ...
while($row = mysqli_fetch_assoc($sql)) {
 ....
  $dataset[]=array(
     "Header1" : $string_val1,
     "Header2" : $string_val1,
     "Header3" : $string_val1
  );
}

... here

1 Comment

Thanks for your answer. I tried that. And on top of that, I tried to add "json" as the datatype in ajax but with or without, I get the same error messages. The difference is, without json_encode, the formatting is closer to the original (otherwise, it's very convoluted). About the "array". If I do that, my php formatting doesn't make any sense then as it would not be a string anymore. And if I have to change that string to an actual array, then I'm lost as I don't know how to remotely generate the same dataSet on the jQuery side. You might be right, but I need more guidance then..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.