Kieron606
Kieron606

Reputation: 613

Datatables and ajax data formatting?

I am using Datatables and I want to be able to send an AJAX request to get my data.

My jQuery -

$('.valid-tags').DataTable( {
    "ajax": {
        "url": "/ajax/getValidTags.php",
        "type": "POST",
        "data": {
            ruleID: ruleID
        }
    }
} );

This is the data returned from the ajax request -

{"data":["K":2,"B":1,"C":2]}

Im expecting to see 'K', 'B', 'C' under tag name in their own rows.

enter image description here

My Datatables doesn't load any data though?

I need to be able to wrap each key value pair in its own array so this -

{"data":["K":2,"B":1,"C":2]}

Would be -

{"data":[["K":2],["B":1],["C":2]]}

This is the PHP that builds it (where do i wrap the key values in an object so it like the above)?-

$validTagsArray = array();
$validArray = array();

foreach ($cursor as $key => $value) {
  foreach ($value['AutoFix'] as $k => $v) {
    $x = 0;
    foreach ($v as $key => $value) {
      $x++;
      $validValueCount = $validTagsArray[$k] = $x;
    }
  }
}

$validArray['data'] = array($validTagsArray);


echo json_encode($validArray);

Upvotes: 1

Views: 3622

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58870

Change the format of the JSON that you're returning as shown below. See Data source types for more information.

{
    "data": [
        [ "K", 2 ],
        [ "B", 1 ],
        [ "C", 2 ]
    ]
}

Change your initialization options as shown below.

$('.valid-tags').DataTable( {
    "ajax": {
        "url": "/ajax/getValidTags.php",
        "type": "POST",
        "data": {
            ruleID: ruleID
        }
    },
    "columnDefs": [{
       "targets": 2,
       "render": function(data, type, full, meta){
          return '<button type="button">Manage</button>';
       }
    }]
} );

See this jsFiddle for code and demonstration.

Upvotes: 2

Related Questions