Reputation: 709
Have a simple question here but am new to datatables so forgive my ignorance: I have a query of rows that I placed in an array and then encoded it in JSON format, how can I send this array to datatables in order to populate each row? I've looked at other threads but they are using ajax to externally reference the script whereas mine is located on the same page (not sure if that makes a difference). My script looks like this:
<?php
if(isset($_POST['post_id'])){
$in = $_POST['post_id'];
}
$data = array();
foreach ($in as $id){
$query = $link->prepare("SELECT provider_num, provider_name, 233_net_charity_care, 291_cost_of_non_mcr_bad_debts, 301_cost_of_uncomp_care
FROM `s10`
WHERE `id` = :id");
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
$data[] = $results;
}
json_encode($data);
?>
Where post_id is the initial array of id values submitted to the page from the previous form, for simplicity's sake lets say that I only have one row submitted this time.
The JSON output looks like this
[{"provider_num":"140124","provider_name":"JOHN H. STROGER JR. HOSP OF COOK CTY","233_net_charity_care":"163307737","291_cost_of_non_mcr_bad_debts":"181677291","301_cost_of_uncomp_care":"344985028"}]
In what way do I then initialize datatables to receive this data
So far I have:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "", <== What goes here?
"columns": [
{ "data": "provider_num" },
{ "data": "provider_name" },
{ "data": "233_net_charity_care" },
{ "data": "291_cost_of_non_mcr_bad_debts" },
{ "data": "301_cost_of_uncomp_care" }
]
} );
} );
Any insight would be great, I'm pretty new to jquery in general so apologies if this is an easy question. I tried to read the documentation but had trouble relating to it.
Thanks in advance
Upvotes: 0
Views: 6229
Reputation: 431
The first thing is, if your frontend script and server script(php) is in the same page, you don't need to use ajax.
you can simply set the data like this after your php script
var tableData = <?php echo json_encode($data); ?>;
Then in datatable initialize method, use this
$(document).ready(function() {
$('#example').dataTable({
"aaData": tableData,
"aoColumns": [
{ "data": "provider_num" },
{ "data": "provider_name" },
{ "data": "233_net_charity_care" },
{ "data": "291_cost_of_non_mcr_bad_debts" },
{ "data": "301_cost_of_uncomp_care" }
]
});
});
Upvotes: 1