1

I'm trying load json data on table using datatables

The return of json from php is like this:

data = {
  "CLIENTES": {
    "0": {
      "ID": "1",
      "NOME": 'GABRIEL'
    },
    "1": {
      "ID": "2",
      "NOME": 'RODRIGUES'
    }
  }
}

In the documentation columns data they say that I need to follow this structure:

table.DataTable({
  "ajax": url,
  columns: [
    {"data": "CLIENTES.ID"},
    {"data": "CLIENTES.NOME"}
  ]
});

But dont work, and we know that the right acess to de data index is this way:

{"data": "CLIENTES['0'].ID"},
{"data": "CLIENTES['1'].ID"},

But need's to be dynamically, how can I do this?

3 Answers 3

1

You should create new data for datatable without CLIENTES .... map is an option.

  $(document).ready(function() {
    data = {
      "CLIENTES": {
        "0": {
           "ID": "1",
           "NOME": 'GABRIEL'
        },
       "1": {
           "ID": "2",
           "NOME": 'RODRIGUES'
         }
       }
     };


   var newData = $.map(data.CLIENTES, function(el) { return el });

   $('#example').DataTable({
       data: newData,
       columns: [
       {"data": "ID"},
       {"data": "NOME"}
       ]
    });

  });

example: https://jsfiddle.net/cmedina/7kfmyw6x/5/

Sign up to request clarification or add additional context in comments.

1 Comment

This is a good answer if you haven't got say over what data you receive, but if you do then sending through only the required data is a much better approach.
0

If you remove the 'CLIENTES' outer array and only return an array of the results in your PHP, you will be able to refer to the values like this:

    table.DataTable({
        "ajax": url,
        columns: [
          {"data": "ID"},
          {"data": "NOME"}
        ]
    });

Comments

0

you can do things to an object dynamically by using for var in

var myArray = [] //an  empty array

for(var i in data){
    myData.push({"data": "CLIENTES[i].ID"})
    myData.push({"data": "CLIENTES[i].NOME"})        
}    

then later you can do this

table.DataTable({
    "ajax": url,
    columns: myArray
});

but I suspect the way you write {"data": "CLIENTES[i].ID"} is wrong, though i havent used datatables before.

maybe something like this is more correct? it's how you usually get to object properties

for(var i in data){
    myData.push({"data": data.CLIENTES[i].ID})
    myData.push({"data": data.CLIENTES[i].NOME})        
}    

Comments

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.