Reputation: 850
I am unable to populate a datatable using ajax data source. I am using Codeigniter version 3 and WAMP v 3.2.0. VIEW Code:
<table class="table table-striped table-bordered table-hover" cellspacing="0" id="farmer_data_table">
<thead>
<tr>
<th>First Name</th>
<th>Gender</th>
<th>Phone No.</th>
<th>City/Town</th>
<th>PIN</th>
<th>State</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#farmer_data_table').DataTable( {
"ajax": "<?=site_url();?>nautics/farmers/fetch_farmer_data/",
"columns": [
{ "data": "first_name" },
{ "data": "gender" },
{ "data": "phone_number" },
{ "data": "city_town" },
{ "data": "pin_code" },
{ "data": "state" }
]
} );
});
Controller Code:
public function fetch_farmer_data()
{
$url="http://<IP Address>/api/v1/form-data/all-record";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'x-access-token: ' . $this->session->userdata('access_token')
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response,true);
//var_dump($result);
}
var_dump($result) shows data as:
array (size=1)
'data' =>
array (size=6)
0 =>
array (size=28)
'active' => boolean true
'address' => string 'Golghat,-' (length=9)
'age' => int 27
'alt_phone_number' => string '' (length=0)
.................................more key-value pairs
1 =>
array (size=28)
'active' => boolean true
'address' => string 'Golaghat,-' (length=10)
'age' => int 27
'alt_phone_number' => string '' (length=0)
.................................more key-value pairs
The error message is:
DataTables warning: table id=farmer_data_table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
Can anyone please tell me if my json data is in incorrect format or the entire code to populate datatable is wrong. Thanks in advance.
Upvotes: 1
Views: 72
Reputation: 26
Returning the response as the output will do if the response is in json, so there is no need to encode or decode remove the line $result = json_decode($response,true); completely in addition to what @alexktz has said and check
Upvotes: 1
Reputation: 58
Your Controller does not return something.
You are doing $result = json_decode($response,true);
which creates the JSON, but the controller does not offer it to the request site.
You should have something like that after the line mentioned above:
return $this->output
->set_content_type('application/json')
->set_output($result);
Edit:
The line $result = json_decode($response,true);
is also wrong, you have an Array, which you wanted to have converted to a JSON. So you have to use json_encode
instead for the response.
Upvotes: 1