I would like to know how could I make a data table row with Dynamic data.
I have this table:
But I want to show the red data dynamically according to my user roles.
For example if my role is equal to supervisor show him one buttons or if my role is different to this one show to user other buttons
this is my html table:
<div class="table-responsive-lg table-responsive-md">
<table id="table" class="table table-hover">
<thead>
<tr>
<th></th>
<th>Solicitante</th>
<th>Dia de solicitud</th>
<th>Estatus</th>
<th>Acciones</th>
</tr>
</thead>
</table>
</div>
And I call this method in document ready function
table = $('#table').DataTable({
'data': data
, 'columns': [
{
'className': 'details-control',
'orderable': false,
'data': null,
'defaultContent': ''
},
{ 'data': 'name' },
{ 'data': 'request.dateRquest' },
{ 'data': 'request.status' },
{
"className": '',
"orderable": false,
"data": null,
"defaultContent": '<button class= "btn btn-success btn-circle asignar" title="Asignar"> <i class="material-icons">assignment_ind</i></button>'+
" "+
'<button class= "btn btn-danger btn-circle rechazar" title="Rechazar"> <i class="material-icons">close</i></button>'
}
],
'order': [[1, 'asc']]
})
Can I iterate the data that i want to put on my table? In the picture I have a column call estatus if the estatus is different to pending I want to make other action with the button.
So I need to check the role of person that is sign in and check the status of each row
I want to make someting like this:
If(role == xRole && data.status != 'Pending'){
Change style of button
Put a different class for example change .Assign to .CloseRequest
}
If I knew how to interactue with the data that I'm going to put in the rows before the table was maked it will be more easy
It is possible?
Change
"defaultContent": '<button class= "btn btn-success btn-circle asignar" title="Asignar"> <i class="material-icons">assignment_ind</i></button>'+
" "+
'<button class= "btn btn-danger btn-circle rechazar" title="Rechazar"> <i class="material-icons">close</i></button>'
to
"defaultContent": getButtons()
and define this function:
function getButtons() {
switch (role) {
case "admin": return "sometemplate1";
default: return "sometemplate2";
}
}
just make sure that role is properly defined.
Related
On the list page user can edit info by click on Edit button and open details page for edit data.
After edit done return list page. This my source code
My JS listUser.js is embbed in jsp file at the bottom listusers.jsp
<div class="c-body">
<main class="c-main">
<div class="container-fluid">
<div class="fade-in" id="content">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-sm-4">List Users</div>
<div class="col-sm-8 text-right">
<button id="create_user" type="button" class="btn btn-primary">Tạo mới</button>
</div>
</div>
</div>
<div class="card-body">
<table id="userTable" class="table table-striped table-bordered datatable">
<thead>
<tr>
<th>Username</th>
<th>Full Name</th>
<th>Site</th>
<th>Roles</th>
<th>Areas</th>
<th>Team</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src="${contextPath}/user/listUser.js"></script>
</div>
</div>
</main>
</div>
listUser.js
$( document ).ready(function() {
var userTable = $('#userTable').DataTable( {
"processing": true,
"serverSide": true,
"pageLength": 10,
"ajax": {
"url": "/user/paginated",
"data": function ( data ) {
}},
"columns": [
{ "data": "username", "name" : "Username", "title" : "Username", "defaultContent" : ""},
{ "data": "full_name", "name" : "Full Name" , "title" : "Full Name", "defaultContent" : ""},
{ "data": "site_code", "name" : "Site" , "title" : "Site", "defaultContent" : ""},
{ "data": "user_roles", "name" : "Roles", "title" : "Roles", "defaultContent" : ""},
{ "data": "user_areas", "name" : "Areas", "title" : "Areas", "defaultContent" : ""},
{ "data": "team_code", "name" : "Team", "title" : "Team", "defaultContent" : ""},
{ "data": "status", "name" : "Status", "title" : "Status", "defaultContent" : ""},
{ "targets": "no-sort", "orderable": false, "data": "null", "name" : "Thao tác", "title" : "Thao tác", "defaultContent" : "<button id='updateUser' name='updateUser' class='btn btn-primary btn-edit' type='button' aria-pressed='true'>Sửa</button>"}
]
});
$('#userTable').on('click', '.btn-edit', function(){
var data = userTable.row( $(this).parents('tr') ).data();
//alert(data.user_id);
let url = "user/updateUser?id=" + data.user_id;
$("#content").load(url);
});
$(document).on('click', '#update_user', function(){
updateUser();
});
function updateUser() {
...
var data = {
...
};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
if(myObj.status == "1"){
$("#content").load("user/list");
}
}
};
xhr.open("POST", "/user/update");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(json);
}
});
The problem I occurred DataTables warning: table id=userTable - Cannot reinitialise DataTable.
Thanks you.
From DataTable Docs (first result in search engine with the warning message you provided):
DataTables has a wide range of configuration options which can be used to customise the table at initialisation time, but only at initialisation time. After a DataTable has been initialised any attempt to use these options will result in an error.
Simply put, DataTables does not allow initialisation options to be altered at any time other than at initialisation time. Any manipulation of the table after initialisation must be done through the API [...]
You are not showing how you initialize DataTable, so I can't help you further, unless you update your answer with more information.
Edit
After gathering more info from you, I now can understand what you are trying to do.
Essentially: DataTables expects it's DOM elements to be managed by itself. Once you initialize a DataTable, you should not manipulate any DOM related to it. If you want to show something like the user editing page and go back to the table after save, you need to choose one of the next 2 options:
Completely unmount the DataTable before showing the user edit page and re-initialize it after saving user data and gathering new DataTable data from server.
Don't detach DataTable DOM: show user form in a modal, or hide the DataTable instead of removing it, and unhide it again after user data has been saved. Updated data will need to be reinjected into a living DataTables, which I think will need the use of the .ajax.data initialization option.
Depends on how much data is being transferred and processed I'd choose one or the other.
I have function delete on my table ( using datatables) this delete is work normally but i want to add some pop up alert like "onclick" on my delete , but its didnt work on my button
public function indexDataTables_pns()
{
$pns = Data_pns::with('users','master_golongan','master_jabatan')->get();
return Datatables::of($pns)->addIndexColumn()
->addColumn('Nama', function ($pns) {
return ''.$pns->users->nama.'';
})
->editColumn('edit', function ($pns) {
return '<i class="glyphicon glyphicon-edit"></i>';
})
->editColumn('hapus', function ($pns) {
$c = csrf_field();
$m = method_field('DELETE');
return "<form action='/delete/$pns->id' method='POST')>
$c
$m
<button style='margin-left:10px; width: 30px;' type='submit'
class='btn btn-xs btn-danger delete' onclick='return
confirm('do you want to delete this data ?')'>
<i class='glyphicon glyphicon-remove-circle'></i>
</button>
</form>";
})
->rawColumns(['Nama' => 'Nama','hapus' => 'hapus','action' => 'action','edit'=>'edit'])
->make(true);
}
its didnt work
i trying adding class
<form action='/delete/$pns->id' method='POST' class='delete-form'>
and add this script
<script>
$('.delete-form').submit(function(event){
if(!confirm('Anda yakin mau menghapus item ini ?')){
event.preventDefault();
}
});
but still didnt work . i put this on under my view .
i try to add onsubmit like this
<form onsubmit='return confirm('Anda yakin mau menghapus item ini ?')'>
still didnt work , iam from this thread this link , but i didnt find the answer ..
look this image
can someone help me ?
UPDATE
i tryng add this form class
return "<form action='/delete/$pns->id' method='POST' class='delete-form')>
this pop up is showing after i click this delete button but this message is null/empty ,
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: '{!! route('d_pns') !!}',
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
{ data: 'Nama', name: 'Nama'},
{ data: 'NIP_lama', name: 'NIP_lama'},
{ data: 'NIP_baru', name: 'NIP_baru'},
{ data: 'TMT_CPNS', name: 'TMT_CPNS'},
{ data: 'TMT_PNS', name: 'TMT_PNS'},
{ data: 'TMT_gol_ruang', name: 'TMT_gol_ruang'},
{ data: 'master_golongan.golongan', name: 'master_golongan.golongan'},
{ data: 'master_jabatan.nama_jabatan', name: 'master_jabatan.nama_jabatan'},
{ data: 'edit', name: 'edit', orderable: false, searchable: false},
{ data: 'hapus', name: 'hapus', orderable: false, searchable: false},
],
});
})
$('.delete-form').submit(function(event){
if(!confirm('Anda yakin mau menghapus item ini ?')){
event.preventDefault();
}
});
</script>
#endpush
why this message on confirm is empty ?
Your 1st attempt issue looks to be escaping the quotes " and '. try putting your message inside double quotes " ". This should resolve your problem
<button style='margin-left:10px; width: 30px;' type='submit'
class='btn btn-xs btn-danger delete' onclick='return
confirm("do you want to delete this data ?")'>
<i class='glyphicon glyphicon-remove-circle'></i>
</button>
SOLVED
Need to add
<script type="text/javascript">
function confirm_delete() {
return confirm('Apakah anda yakin untuk menghapus data ini ? ');
}
</script>
and add onclick return confirm_delete()
I will be dropping this for anyone that need to know how to use onclick from laravel yajra serverside.
$datatable = datatables()->collection($data)
->addColumn('action', function($data){
$button = '
<button type="button" data-security="'.$data->security.'" class="btn btn-warning btn-sm" onclick="OrderTicket(\''.$data->security.'\')">Sell
</button>
<button type="button" data-security="'.$data->security.'" class="btn btn-info btn-sm" onclick="createRequest(\''.$data->security.'\')">Buy
</button>
';
return $button;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
return $datatable;
All you have to do is to escape the strings onclick="OrderTicket(\''.$data->security.'\')"
I have a table that I am using jQuery Datatables with.
Picture:
Scenario:
As you can see in the picture, there is a Delete link. When that link is clicked, a modal pop-up will show asking the user if they really want to delete that item. If yes, delete.. if no.. cancel out of the modal.
What I want:
When a user decides to delete an item and confirms it.. I would like to change the status of that item to "Deleted", via ajax. I am able to change the value, but that value does not show in the table. I have researched this for a couple of days now, but nothing seems to work.
My Code
<table id="Item-Table" class="table table-bordered">
<thead>
<tr>
<th class="text-center">
#Html.DisplayNameFor(model => model.AssetTag)
</th>
<th class="text-center">
#Html.DisplayNameFor(model => model.codeMakeModel.MakeModel)
</th>
<th class="text-center">
#Html.DisplayNameFor(model => model.codeStatu.Status)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class="text-center">
<td>
#Html.ActionLink(item.AssetTag, "Edit", new { id = item.Id })
</td>
<td>
#Html.DisplayFor(modelItem => item.codeMakeModel.MakeModel)
</td>
<td class="changeStatus">
#Html.DisplayFor(modelItem => item.codeStatu.Status)
</td>
<td>
Delete
</td>
</tr>
}
</tbody>
</table>
#section scripts{
<script>
var settings = {};
settings.baseUri = '#Request.ApplicationPath';
var infoGetUrl = "";
if (settings.baseUri === "/projectonservername") {
infoGetUrl = settings.baseUri + "/api/itemsapi/";
} else {
infoGetUrl = settings.baseUri + "api/itemsapi/";
}
$(document).ready(function () {
var itemsTable = $("#Item-Table").DataTable({
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [3] },
{ "bSearchable": false, "aTargets": [3] }
]
});
$("#Item-Table").on("click",
".js-item-delete",
function() {
var link = $(this);
bootbox.confirm({
title: "Delete Item?",
message: "Are you sure you want to delete this item?",
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function(result) {
if (result) {
toastr.options = {
timeOut: 5000
}
$.ajax({
url: infoGetUrl + link.data("item-id"),
method: "DELETE",
success: function (result) {
//itemsTable.cell(itemsTable.row(this), 2).data("Deleted");
//itemsTable.draw();
//itemsTable.reload();
console.log(itemsTable.cell(itemsTable.row(this), $('.changeStatus')).data());
itemsTable.cell(itemsTable.row(this), $('.changeStatus')).data("Deleted").draw();
console.log(itemsTable.cell(itemsTable.row(this), $('.changeStatus')).data());
toastr.success("Item successfully deleted");
},
error: function(jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
console.log(jqXHR);
toastr.error(status + " - " + errorThrown, "Sorry, something went wrong.");
}
});
}
}
});
});
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
})
</script>
}
What I am Receiving
In the above code, specifically these lines:
console.log(itemsTable.cell(itemsTable.row(this), $('.changeStatus')).data());
itemsTable.cell(itemsTable.row(this), $('.changeStatus')).data("Deleted").draw();
console.log(itemsTable.cell(itemsTable.row(this), $('.changeStatus')).data());
I am logging the value of the cell before I update that cell value, then changing the cell value, then logging the new/updated cell value.
Here is what I am receiving in the console:
But the table is not updating, or rather.. redrawing itself to show deleted.. the only way for it show deleted is to refresh the page which defeats the purpose of ajax..
How do I get the table to update the cell value without a page refresh?
Any help is appreciated.
I was able to answer this myself with some help of DavidDomain in the comments.
He suggested that I could possibly be selecting an incorrect row. So that gave me the idea to get the row at the start of this by adding:
$("#Item-Table").on("click",
".js-item-delete",
function() {
var link = $(this);
var row = $(this).parents("tr"); // get row element
Then set the cell data using that variable like so:
itemsTable.cell(itemsTable.row(row), $('.changeStatus')).data("Deleted").draw();
This worked and successfully drew the table with the updated value.
I have a server-side dataTable where when I click each row, I want it to show its Edit and Delete action links for the user to click on it and be directed to those pages.
#*<td>
#Html.ActionLink("Edit", "Edit", new { id = item.DepartmentID }) |
#Html.ActionLink("Details", "Details", new { id = item.DepartmentID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.DepartmentID })
</td>*#
When I search on their website, they use the editor for datatables. But I am not able to implement the actionlinks with the editor for many undefined errors.
Can someone please assist me to figure out how to make the on click event work?
This is the script for the dataTable
init: function () {
dt = $('#datatableServer').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url":
"#Url.Action("DataHandler","Department")"
},
"columns": [
{ "data": "Name",
"searchable": true },
{
"data": "Budget", "render": $.fn.dataTable.render.number(',', '.', 0, '$'),
"searchable": false },
{ "data": "StartDate",
"searchable": false,
"type" : "datetime"},
{ "data": "Administrator",
"searchable": true }
],
............
departmentsList.init();});
$('#datatableServer tbody').on('click', 'tr', function () {
//editor.edit(this, 'Edit record', {
//"label": "Update",
//"fn": function () {
//editor.submit()
//}
//})
console.log('clicked');
console.log(dt.row(this).data().DT_RowId); // DT_RowId is each row's Id
});
I have the DT_RowId getting the id for each table row for my data.
var data = query.Select(a => new DepartmentData
{
DT_RowId = a.DepartmentID.ToString(),
Name = a.Name,
..........
}).ToList();
First thing first
When I have them in my , my dataTable does not show.
The number in your column should match the number of you have. From what i can see, you specified 4 columns
"columns": [
{ "data": "Name", "searchable": true },
{ "data": "Budget", "render": $.fn.dataTable.render.number(',', '.', 0, '$'), "searchable": false },
{ "data": "StartDate", "searchable": false, "type" : "datetime"},
{ "data": "Administrator", "searchable": true }
]
but you also have an action column where your Actionlinks sit. So i suggest adding an addtional data column
{ data: "Action" }
Also make sure your have five header columns too
<thead>
<tr>
<th>Name</th>
<th>Budget</th>
<th>StartDate</th>
<th>Administrator</th>
<th>Action</th>
</tr>
</thead>
Now next thing, i haven't acutally tried to use their editor before, the way i do it is to use my own modal, any modal will do, bootstrap modal is an good option.
For example, you specify a modal in your dataTable view, I place it at the end of the page
<div id="companyModal" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myCompanyModalLabel"></h3>
</div>
#{Html.RenderAction("CompanyModal", "CV");}
</div>
</div>
</div>
I like to use ViewModal in my modal, so i do RenderAction to get all the goodies from ViewModal validation. Of course, you can do #Html.Partial() too instead of RenderAction, RenderAction only if you want to get some value for the ViewModel before returning it.
[ChildActionOnly]
public ActionResult CompanyModal()
{
var model = new CompanyViewModel();
return PartialView("~/Views/Dashboard/CV/_CompanyModal.cshtml", model);
}
The partial view:
#model XXX.CompanyViewModel
<form id="companyForm" style="margin: 0px;">
#Html.AntiForgeryToken()
<div class="modal-body">
#Html.HiddenFor(m => m.CompanyId)
<div class="row-fluid">
<div class="span6">
#Html.LabelFor(m => m.CompanyName)
#Html.TextBoxFor(m => m.CompanyName, new { #class = "input-block-level" })
#Html.ValidationMessageFor(m => m.CompanyName)
</div>
<div class="span6">
#Html.LabelFor(m => m.JobTitle)
#Html.TextBoxFor(m => m.JobTitle, new { #class = "input-block-level" })
#Html.ValidationMessageFor(m => m.JobTitle)
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
<button id="companyEditSubmitBtn" name="edit" class="ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" type="button">Save</button>
</div>
</form>
Now on to the script:
//init dataTable
var cTable = $("#company-table").dataTable();
//open work experience edit modal
$("#company-table").on("click", ".companyEditBtn", function () {
//do
$("#myCompanyModalLabel").text("Edit Work Experience");
//get current position
position = cTable.fnGetPosition((this).closest("tr"));
data = cTable.fnGetData(position);
//set values to modal
$("#companyModal #CompanyId").val(data[0]);
$("#companyModal #CompanyName").val(data[1]);
$("#companyModal #JobTitle").val(data[2]);
//open modal
$("#companyModal").modal("show");
});
After you open the modal, post the value to your server to save using ajax:
//work experience edit
$("#companyEditSubmitBtn").click(function () {
//get the form
var form = $("#companyForm");
//validate form
if (!form.valid()) {
return;
}
//serialize the form
serializedForm = form.serialize();
//ajax post
$.ajax({
url: "#Url.Action("CompanyEdit", "CV")",
type: "POST",
data: serializedForm,
beforeSend: function () {
l.ladda("start");
},
success: function (result) {
if (result.success) {
//update row of table
cTable.fnUpdate([
result.id,
result.name,
result.title,
"<button class='companyEditBtn btn' title='Edit Work Experience'><i class='icon-pencil'></i></button>" + " " + "<button class='companyDeleteBtn btn' title='Delete Work Experience'><i class='icon-trash'></i></button>"
], position);
toastrSuccess(result.message);
} else {
toastrError(result.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
toastrError(textStatus);
},
complete: function () {
//stop ladda button loading
l.ladda("stop");
//hide modal
$(".modal").modal("hide");
}
});
});
And your edit controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CompanyEdit(CompanyViewModel model)
{
if (ModelState.IsValid)
{
var company = repository.FindCompany(model.CompanyId);
if (company != null)
{
try
{
//map automapper
model.Description = model.Description.Replace(Environment.NewLine, "<br />");
mapper.Map(model, company);
repository.EditCompany(company);
return Json(new { success = true, message = "Wokr Experience Edited", id = company.CompanyId, title = company.JobTitle, name = company.CompanyName });
}
catch (Exception ex)
{
return Json(new { success = false, message = string.Format("{0}", ex) });
}
}
else
{
return Json(new { success = false, message = "Work Experience not found" });
}
}
return Json(new { success = false, message = "Modal state is not valid" });
}
Another thing to mention, instead of using a foreach loop, use DisplayTemplate,
where the Companies property is an IEnumerable which will
automatically do the looping and render the CompanyViewModel.cshtml
display template for each item of this collection.
Source here
<table id="company-table" class="table table-striped table-bordered table-hover dataTables" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Company</th>
<th>Title</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#Html.DisplayFor(m => m.Companies)
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Company</th>
<th>Title</th>
<th>Action</th>
</tr>
</tfoot>
</table>
And specify your display template inside Shared -> DisplayTemplates -> CompanyViewModel.cshtml
#model Taw.WebUI.Models.CompanyViewModel
<tr>
<td>
#Html.DisplayFor(m => m.CompanyId)
</td>
<td>
#Html.DisplayFor(m => m.CompanyName)
</td>
<td>
#Html.DisplayFor(m => m.JobTitle)
</td>
<td>
<button class="companyEditBtn btn" title="Edit Work Experience"><i class="icon-pencil"></i></button>
<button class='companyDeleteBtn btn' title="Delete Work Experience"><i class="icon-trash"></i></button>
</td>
</tr>
I have a mysql table with about 30000 rows. I have to put all rows in a DataTable and load each segment each time a table page is loaded (when you click on pagination). I saw that I can use the deferLoading parameter in my JS, but when I use it my pages are not loading. As you can see, I have to load images, so I absolutely have to do a light loading of the content...
Here is my HTML :
<table class="table table-striped table-bordered table-hover datatable products-datatable">
<thead>
<tr>
<th></th>
<th><?=_("Product")?></th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th><?=_("Product")?></th>
<th></th>
</tr>
</tfoot>
</table>
Here is my JS :
var table = $('.products-datatable').dataTable( {
"order": [[ 1, "asc" ]],
"processing": true,
"serverSide": true,
"deferLoading": 30000,
"ajax": {
url: location.protocol + '//' + location.hostname + '/ajax/products.php?action=list',
type: "POST"
},
"columns": [
{ "data": "image",
"orderable": false,
"width": "80px" },
{ "data": "product" },
{ "data": "action",
"orderable": false,
"width": "20px",
"sClass": "class",
}
]
});
Here is my AJAX :
$req = $pdo->prepare('SELECT product_id, name FROM products');
if ( $req->execute() ) {
if ($req->rowCount()) {
$result['draw'] = 1;
$result['recordsTotal'] = $req->rowCount();
$result['recordsFiltered'] = 10;
$result['data'] = array();
$result['DT_RowId'][] = array();
while( $row = $req->fetch() ) {
if ($row['name']) { $name = $row['name']; } else { $name = "N/A"; }
$result['data'][] = array( "DT_RowId" => $row['product_id'],
"DT_RowClass" => 'myclass',
"image" => '<img src="' . HOSTNAME.'assets/img/products/' . $row['product_id'] . '.jpg" class="product_thumb">',
"product" => '' . $name . '',
"action" => "<i class=\"fa fa-close fa-2x text-danger\"></i>"
);
}
}
}
$req->closeCursor();
I'm sure there is something I missed... :-(
I believe you don't need to use deferLoading to benefit from server-side processing.
Your current script just returns all records and doesn't do sorting or filtering. You need to use ssp.class.php (available in DataTables distribution package) or emran/ssp class to correctly handle AJAX requests on the server.
DataTables library will send start and length parameters in AJAX request indicating which portion of the data is needed and your server-side processing class will correctly handle it for you.
Please see an example of server-side processing for more information.