CodeIgniter4 DataTables Usage - Object Data Source
Table Customers
Cust. No | Name | Phone | City | Country | Postal Code |
---|
Note
This sample database is downloaded from : https://www.mysqltutorial.org/mysql-sample-database.aspx/
Controller
Set
toJson()
argument to true
it will responds with an array of objects
use \Hermawan\DataTables\DataTable;
public function basic_object()
{
$db = db_connect();
$builder = $db->table('customers')->select('customerNumber, customerName, phone, city, country, postalCode');
return DataTable::of($builder)->toJson(true);
}
Javascript
on DataTables options need set
columns
argument to make it works. Then define data
property with column name
$(document).ready(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
ajax: '/ajax-datatable/basic-object',
columns: [
{data: 'customerNumber'},
{data: 'customerName'},
{data: 'phone'},
{data: 'city'},
{data: 'country'},
{data: 'postalCode'},
]
});
});
AJAX Response :
{
"draw": "1",
"recordsTotal": 122,
"recordsFiltered": 122,
"data": [
{
"customerNumber": "103",
"customerName": "Atelier graphique",
"phone": "40.32.2555",
"city": "Nantes",
"country": "France",
"postalCode": "44000"
},
{
"customerNumber": "112",
"customerName": "Signal Gift Stores",
"phone": "7025551838",
"city": "Las Vegas",
"country": "USA",
"postalCode": "83030"
},
{
"customerNumber": "114",
"customerName": "Australian Collectors, Co.",
"phone": "03 9520 4555",
"city": "Melbourne",
"country": "Australia",
"postalCode": "3004"
},
{
"customerNumber": "119",
"customerName": "La Rochelle Gifts",
"phone": "40.67.8555",
"city": "Nantes",
"country": "France",
"postalCode": "44000"
},
{
"customerNumber": "121",
"customerName": "Baane Mini Imports",
"phone": "07-98 9555",
"city": "Stavern",
"country": "Norway",
"postalCode": "4110"
},
{
"customerNumber": "124",
"customerName": "Mini Gifts Distributors Ltd.",
"phone": "4155551450",
"city": "San Rafael",
"country": "USA",
"postalCode": "97562"
},
{
"customerNumber": "125",
"customerName": "Havel & Zbyszek Co",
"phone": "(26) 642-7555",
"city": "Warszawa",
"country": "Poland",
"postalCode": "01-012"
},
{
"customerNumber": "128",
"customerName": "Blauer See Auto, Co.",
"phone": "+49 69 66 90 2555",
"city": "Frankfurt",
"country": "Germany",
"postalCode": "60528"
},
{
"customerNumber": "129",
"customerName": "Mini Wheels Co.",
"phone": "6505555787",
"city": "San Francisco",
"country": "USA",
"postalCode": "94217"
},
{
"customerNumber": "131",
"customerName": "Land of Toys Inc.",
"phone": "2125557818",
"city": "NYC",
"country": "USA",
"postalCode": "10022"
}
]
}