Datatables AJAX - passing an array

datatables array of objects
datatables ajax pagination
datatables ajax columns
jquery datatables ajax json example
datatables ajax data example
datatables nested array of objects
datatables json array
jquery datatables ajax json example php

(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!

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;
}

Ajax and custom parameters, Hi, I'm a noob with php, java, and so on. I am trying to get data from several tables in my mysql server. A JavaScript Array can be used to pass the group of related values as data to the $.ajax for processing and get the response. E.g. pass all checked checkboxes values, selected values from the list. In this tutorial, I show how you can pass JavaScript Array to an AJAX request with an example.

<?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

ajax, Note that DataTables expects the table data to be an array of items in the data As an object, the ajax object is passed to jQuery.ajax allowing fine control of the� Initially, when the page loaded Datatables is generated with complete posts and when we pass from and to dates as custom ajax request in Datatables we get a filtered result. You can pass as many numbers of custom parameters as you can in ajax request but for sake of simplicity of this tutorial, I am passing only two. Note

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!

Flat array data source, The example below shows ajax.dataSrc being used as an empty string. This tells DataTables that the JSON loaded is a plain array, not an object with an array� The array is populated from an ajax call. I guess another way of putting this is how can I set the values for this update method and not hardcode them? kthorngren Posts: 9,526 Questions: 25 Answers: 2,194

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"
                                  }
                               ]
                         });

Nested object data (arrays), Nested object data (arrays). The information read from an Ajax data source can be arbitrarily complex, but still be displayed by DataTables through the� I have a custom form for data entry. I would like to include a DataTable in the custom form, loaded from AJAX. However, I also want to pass an ID to the load script that relates to the row being edited.

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

Datatables AJAX - passing an array, 问题: (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� DataTables allows for passing data that can read at the server-side script. In this tutorial, I show how you can add a custom search filter and get records using DataTables in CodeIgniter. Demo Download

How to Send JavaScript Array to the AJAX using jQuery and PHP, A JavaScript Array can be used to pass the group of related values as data to the $.ajax for Duration: 16:01 Posted: Dec 22, 2018 This is achieved using the data DT option in the initialisation object, passing in an array of data to be used (like all other DataTables handled data, this can be arrays or objects using the columns.data DT option).

DataTables example - Javascript sourced data, This is achieved using the dataDT option in the initialisation object, passing in an array of data to be used (like all other DataTables handled data, this can be� DataTables Options snapshot. Ajax Option. And the main option is Ajax which we are going to use for calling an Action Method for getting data to bind DataTables Grid the data is in Json format. For that we are going to pass URL: -"/Demo/LoadData”, this request is Post request. And data type we are going to set as Json.

Using Datatables without ajax call, Hi,there is a way to use Datatables without an ajax call?What i would like to do is: Use the partial page "Table" and pass an array of products@awai The biggest problem is customization. Today, we will be looking at a jQuery DataTable custom search elements on ajax interface. We are built this project on ASP.NET MVC. Background. jQuery DataTable gives ajax interface to us for custom ajax operations. But it wants to give back some values. Ajax sends some values to the server and gets the

Comments
  • set dataType: "json", in ajax.
  • 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.
  • have you added datatable js files?
  • yes. DataTables works for everything else but this.
  • 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) ?
  • Let us continue this discussion in chat.
  • 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