json - How to pass correctly a php json_encode value to a table that is using DataTables plugin?

one text

Solution:

I found a solution. I edited all_payments.php script as below:

<?php

//setup your token payment or others
$token = "PROD_TOKEN";

//setup the request, you can also use CURLOPT_URL
$ch = curl_init('API_URL');

// Returns the data/output as a string instead of raw data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Set your auth headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
   'Content-Type: application/json',
   'Authorization: Bearer ' . $token
   ));

// get stringified data/output. See CURLOPT_RETURNTRANSFER
$data = curl_exec($ch);

// get info about the request
$info = curl_getinfo($ch);

header('Content-Type: application/json');

$new_array = array(); // this array should be empty

$decode = json_decode($data);

// access property of object in array
echo '{"data":';
foreach($decode->results as $item) {
  $new_array[] = array(
    'id' => $item->{'id'},'date_created' => $item->{'date_created'}, 'email' => $item -> payer ->{'email'}, 'total_paid_amount' => $item -> transaction_details ->{'total_paid_amount'}
    );  
}

echo json_encode($new_array);

echo '}';
// close curl resource to free up system resources
curl_close($ch);


?>

On foreach the script get object values and then output results passing json values to Datatables, as code below:

<table id="example" class="display" width="100%">
    
            <thead>
            <tr>
                <th>ID</th>
                <th>Date Created</th>
                <th>Email</th>
                <th>Total</th>
            </tr>
        </thead>
    
</table>

<script>
    $(document).ready(function() {
  
    $('#example').DataTable( {

        "ajax": "all_payments.php",
        "columns": [
            { "data": "id" },
            { "data": "date_created" },
            { "data": "email" },
            { "data": "total_paid_amount",
            
                render: $.fn.dataTable.render.number( ',', '.', 2, '$ ' )
                
            },
        ],
        
    "columnDefs":[
        {"targets":1, render:function(data){
      return moment(data).format('MM/DD/YYYY');
    }},
    
            {"targets": 3,
        "className": 'dt-body-right'}
    
    ]

    });
  
    });
    
    
    </script>

That's it. If anyone would like to improve this code, feel free.

Source