Sorting doesn't work in jQuery DataTables - javascript

I want to implement ordering but it is not working.
Can you tell me the reason why? What do I need to change to make it work so that my data is displayed in order?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring pagination using data tables</title>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- <script type="text/javascript" src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script> -->
<script type="text/javascript" src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
//Plug-in to fetch page data
jQuery.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};
$(document).ready(function() {
var table=$("#table").DataTable( {
"bProcessing": true,
"bServerSide": true,
"sPaginationType": "full_numbers",
"scrollY":"120px",
"scrollCollapse": true,
"order": [[ 3, "desc" ]],
"oLanguage": {
"oPaginate": {
"sNext": '&gt',
"sLast": '&raquo',
"sFirst": '&laquo',
"sPrevious": '&lt'
}
},
"sort": "position",
//bStateSave variable you can use to save state on client cookies: set value "true"
"bStateSave": false,
//Default: Page display length
"iDisplayLength": 10,
//We will use below variable to track page number on server side(For more information visit: http://legacy.datatables.net/usage/options#iDisplayStart)
"iDisplayStart": 0,
"fnDrawCallback": function () {
$('table #table td').bind('mouseenter', function () { $(this).parent().children().each(function(){$(this).addClass('datatable');}); });
$('table #table td').bind('mouseleave', function () { $(this).parent().children().each(function(){$(this).removeClass('datatable');}); });
//Get page numer on client. Please note: number start from 0 So
//for the first page you will see 0 second page 1 third page 2...
//alert("Current page number: "+((this.fnPagingInfo().iPage)+1));
},
"sAjaxSource": "${pageContext.request.contextPath}/EmployeeData",
"aoColumns": [
{ "mData": "firstName" },
{ "mData": "lastName" },
{ "mData": "emp_Id" },
{ "mData": "email_ID" },
{ "mData": "phone_No" },
{ "mData": "city" },
{ "mData": "Edit",
render:function(data ,type,row){
return 'Edit';
},
},
{ "mData": "View",
render:function(data ,type,row){
return 'View';
},
},
{ "mData": "Delete",
render:function(data ,type,row){
/* return '<button><a id="btn" href="${pageContext.request.contextPath}/delete?emp_Id='+row.emp_Id+'">Delete</a></button>'; */
/* return Delete */
return 'Delete';
/* return '<button id="delete_Id" empId='+row.emp_Id+'>Delete</button>'; */
/* return 'Delete'; */
},
},
]
}
);
} );
function deleteEmp(emp_Id){
if(confirm("are you sure want to delete this ID : "+emp_Id)){
window.location = "${pageContext.request.contextPath}/deleteEmp?emp_Id="+emp_Id;
}
else{
return false;
}
}
</script>
<style>
#table{
align:center;
}
#btn{
text-decoration:none;
}
#h{
text-align:center;
color:blue;
}
#link3{
float:right;
margin-right:5px;
}
#link4{
float:right;
}
#brk{
height: 10px;
}
.datatable{
background-color: #ddd !important;
}
</style>
</head>
<body>
<form:form action="" method="GET">
<h2 id="h" >Employee Details<br><br></h2>
<div>
Add New Employee
<a id="link4" href="${pageContext.request.contextPath}/bulkExport">EmployeeBulkExport</a>
<a id="link3" href="${pageContext.request.contextPath}/fileUploadForm">EmployeeImport </a>
</div>
<div id = "brk"></div>
<table width="100%" style="border: 3px;background: rgb(243, 244, 248);"><tr><td>
<table id="table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>firstName</th>
<th>lastName</th>
<th>emp_Id</th>
<th>email_Id</th>
<th>phone_No</th>
<th>City</th>
<th>Edit</th>
<th>View</th>
<th>Delete</th>
</tr>
</thead>
</table>
</td></tr></table>
</form:form>
</body>
</html>

CAUSE
You have server-side processing enabled with "bServerSide": true. In this mode searching, filtering and pagination should be done on the server-side.
Most likely your server-side script (${pageContext.request.contextPath}/EmployeeData) isn't programmed to do so, that's why you don't see ordering/filtering/pagination working.
See manual for more information on processing modes.
SOLUTION
Remove "bServerSide": true to enable client-side processing.
Alternatively, if you have a large dataset you may look into implementing ordering/filtering on the server based on supplied parameters.

Related

JQuery DataTable not working

I'm trying to create table with DataTable library (that using foundation-zurb),
This is the table html code:
<table dir="rtl" id="example" class="display responsive nowrap" cellspacing="0" width="100%; " >
<thead style="margin-top:0%;">
<tr class="top-table" >
<th><label class="tableHeaders">מספר</label></th>
<th><label class="tableHeaders"><fmt:message key="email" /></label></th>
<th><label class="tableHeaders"><fmt:message key="department1" /></label></th>
<th><label style="float:right;"><fmt:message key="role1" /></label></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach items="${listAdmin_user}" var="Admin_user" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${Admin_user.email}</td>
<td>${Admin_user.departmentObj.inCurrentLanguage}</td>
<td>${Admin_user.roleObj.inCurrentLanguage}</td>
<td>
<img src="resources/images/update.gif">
<img src="resources/images/erase.gif">
</td>
</tr>
</c:forEach>
</tbody>
</table>
also I added this scripts to my html file:
(to initial the table and add DataTable files that located in my project folders)
<script src="r/lib/foundation-sites/bower_components/jquery/dist/jquery.js"></script>
<script src="r/lib/foundation-sites/bower_components/foundation-sites/dist/foundation.js"></script>
<script src="r/lib/foundation-sites/bower_components/foundation-sites/dist/foundation.min.js"></script>
<script src="resources/DataTables-1.10.12/DataTables-1.10.12/media/js/jquery.dataTables.min.js"></script>
<script src="resources/Responsive-2.1.0/js/dataTables.responsive.min.js"></script>
<script>
$(document).foundation();
$(document).ready(function() {
var dataTable = $('#example').DataTable(
{
"language": {
"url": "resources/DataTables-1.10.12/DataTables-1.10.12/hebrew.json"
},
"columnDefs": [ {
"targets": [5,6],
"orderable": false
},
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: 1 },
{ responsivePriority: 3, targets: 5 },
{ responsivePriority: 4, targets: 6 }
],
responsive: true,
}
);
$("#searchbox").keyup(function() {
dataTable.fnFilter(this.value);
});
$("#searchbox").on("keyup search input paste cut", function() {
dataTable.search(this.value).draw();
});
});
</script>
(on the end of jsp page).
Here is the links:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/css/foundation.css">
<link href="resources/cssf/addCss.css?version=6" rel="stylesheet" >
<link rel="stylesheet" href="resources/foundation-icons/foundation-icons.css" />
<link rel="stylesheet" href="resources/DataTables-1.10.12/DataTables-1.10.12/media/css/dataTables.foundation.min.css"/>
<link rel="stylesheet" href="resources/DataTables-1.10.12/DataTables-1.10.12/media/css/jquery.dataTables.min.css"/>
<link rel="stylesheet" href="resources/Responsive-2.1.0/css/responsive.dataTables.min.css"/>
<link href="r/css/app.css" rel="stylesheet" >
My problem is that the DataTable not working,
I get error on this line in js file:
i._DT_CellIndex={row:b,column:l};g.push(i);if((!c||n.mRender||n.mData!==l)&&(!h.isPlainObject(n.mData)||n.mData._!==l+".display"))i.innerHTML=B(a,b,l,"display");n.sClass&&(i.className+=" "+n.sClass);n.bVisible&&!c?j.appendChild(i):!n.bVisible&&c&&i.parentNode.removeChild(i);
The error:
Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
I also using DataTable in another pages and its working fine, only on this page I got this error.
Someone have any idea about my problem?
The mismatch in the number of header columns cause this issue, there should be equal number of header columns and the row columns.
Please change your script to below script it will work for you !!!.
<script>
$(document).foundation();
$(document).ready(function() {
var dataTable = $('#example').DataTable(
{
"language": {
"url": "resources/DataTables-1.10.12/DataTables-1.10.12/hebrew.json"
},
"columnDefs": [ {
"targets": [2,3],
"orderable": false
},
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: 1 },
{ responsivePriority: 3, targets: 2 },
{ responsivePriority: 4, targets: 3 }
],
responsive: true,
});
$("#searchbox").keyup(function() {
dataTable.fnFilter(this.value);
});
$("#searchbox").on("keyup search input paste cut", function() {
dataTable.search(this.value).draw();
});
});
</script>

How to receive data of a td element in the server side

<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Modify Index Order</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet"
href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href='<c:url value="/static/css/header.css" />'>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<script
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script
src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js"></script>
<!-- <script src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>
<script src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.draggable.js"></script> -->
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<style type="text/css">
table {
table-layout: fixed;
word-wrap: break-word;
}
th {
text-align: center;
}
#serviceSelect {
text-align: center;
}
#serviceSelect {
margin: auto;
width: 30%;
}
#removeSelect {
text-align: center;
}
#removeSelect {
margin: auto;
width: 30%;
}
#123 {
margin: auto;
width: 50%;
}
p {
font: bold;
}
.editrow {
border: 3px solid red;
}
</style>
</head>
<body>
<jsp:include page="../shared/header.jsp">
<jsp:param value="modifyIndexOrder" name="currentPage" />
</jsp:include>
<form class="form-horizontal" role="form" action="updateIndexOrder"
method=POST id="form2">
<div class="table-responsive12">
<table class="table table-bordered table-striped table-highlight"
id="tab_logic">
<tbody>
<tr>
<th style="width: 20%">IndexOrder</th>
<th style="width: 20%">Name</th>
<th style="width: 20%">CatKey</th>
</tr>
</tbody>
</table>
<table class="table table-bordered table-striped table-highlight"
id="submittable">
<tr id="submit123">
<td colspan="3" align="center">
<div class="form-group">
<button type="submit" class="btn btn-success btn-md" id="submit">Submit</button>
</div>
</td>
</tr>
</table>
</div>
</form>
<script type="text/javascript">
$(function() {
loadTable();
$("#tab_logic").sortable({
items : "tr:not(th)",
helper : "clone",
update : function() {
alert("success");
}
}).disableSelection();
// print();
});
function loadTable(){
$.ajax({
type : "GET",
dataType : 'json',
async : false,
url : "modifyIndex",
success : function(data) {
loadData(data);
},
error : function() {
alert("error");
}
});
}
function loadData(data){
alert("success");
var htm="<tr><th style='width:20%'>IndexOrder</th><th style='width:20%'>Name</th><th style='width:20%'>CatKey</th></tr>";
for(var i=0;i<data.length;i++)
{
htm+="<tr><td name='io"+i+"'>"+data[i].indexOrder+"</td><td name='na"+i+"'>"+data[i].name+"</td><td name='ca"+i+"'>"+data[i].catKey+"</td></tr>";
}
$("#tab_logic").html(htm);
}
function print()
{
var order = $("#tab_logic td");
var i = 1;
var col = 1;
order.each(function() {
var t = $(this).attr('name');
alert(t);
});
}
</script>
</body>
</html>
I have a table in a form which doesn't have any input field but only a table that displays data . i want that on submitting the form i should be able to read the data of the td element of the table in my controller .
Something like request.getParameter("td_name") . I read that name is not a valid attribute for td . SO in this case how can i get the data of the td elements in my controller.
You can go through your table and get all of your tr's or td's, for example:
var products = [];
$('#table tbody tr').each(function (index, tr) {
var product = {
Id: Number($(tr).find('td:nth-child(1)').text()),,
}
products.push(product);
});
$.post('/Url/Post', { products: products }, function (response, status) {
console.log(response);
if (status === 'success') {
alert('Success.');
}
});
You could do this by adding id attribute to your td
example : <td id="mytd">This is some value</td>
Now on your java script you could do something like this:
var tdvalue = document.getElementById ( "mytd" ).innerText;
or in jQuery
var tdvalue = $("#mytd").text();
now all you have to do is pass tdvalue to your request :)

Typeerror D is undefined Jquery Datatables

I have the following code that is suppossed to generate report using datatables. But it keeps on failing giving me the following jquery datatbles error :
TypeError: d is undefined
...=f.nextSibling}else{d=b.anCells;f=0;for(b=d.length;f<b;f++)a(d[f])}return{data:e...
Below is my code that is supposed to generate the view , currently I get only a blank
<!DOCTYPE html>
<html lang="en">
<head>
<!--
-->
<meta charset="utf-8">
<title>Care-tech System</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Out patient Hospital Management System.">
<meta name="author" content="Harris Samuel Dindi">
</head>
<body>
<table id="test_trial" class="test_trial">
<thead>
<tr></tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
</body>
</html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="http://cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
<link href='http://cdn.datatables.net/1.10.5/css/jquery.dataTables.css' rel='stylesheet'>
<script type="text/javascript">
$(document).ready(function () {
$("#test_trial").DataTable({
stateSave: true,
"bautoWidth": false,
"aoColumns": [
{"sTitle": "Commodity No", "mData": "commodity_id"},
{"sTitle": "Commodity Name.", "mData": "commodity_name"
},
{"sTitle": "Strength", "mData": "strength"},
{"sTitle": "Commodity code", "mData": "commodity_code"},
{"sTitle": "Type.", "mData": "commodity_type"},
{"sTitle": "Commodity unit", "mData": "commodity_unit"},
{"sTitle": "Max Stock", "mData": "max_stock"},
{"sTitle": "Min sTOCK", "mData": "min_stock"},
{"sTitle": "Remarks", "mData": "remarks"},
],
"bDeferRender": true,
"bProcessing": true,
"bDestroy": true,
"bLengthChange": true,
"iDisplayLength": 20,
"sAjaxDataProp": "",
"sAjaxSource": '<?php echo base_url() . "pharmacy/commodity_managements"; ?>',
"aaSorting": [[2, "desc"]]
});
});
</script>
How can I do away with the error?
TypeError: d is undefined means your server-side php endpoint URL (pharmacy/commodity_managements) returns no data to the grid. Try to debug your php response.
Ishettyl gave an answer that is partly correct. The Data Table version is current, but the table properties that are being utilized are from the legacy edition of Data Tables. Changing all of your table properties to the 1.10.5 version should fix your issue. (example: change "mData" to "data", ect.)

empty dataTable gird is being shown

I have written a small sample program to bind JSON data in a grid using Datatable
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
</head>
<body>
<table id="example">
<thead>
<tr><th class="site_name">symbol</th><th>qunatity </th></tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(function(){
var r = [
{"symbol":"BPCL","qunatity":"1222"},{"symbol":"HDCF","qunatity":"2333"}
]
$("##example").dataTable({
"aaData":r,
"bJQueryUI": true,
"bDestroy": true,
"iDisplayLength": 50,
"bProcessing": true,
"aaSorting": [[0, 'desc']],
"aoColumns": [
{ "mData": "symbol" },
{ "mData": "qunatity" }
],
});
})
</script>
</body>
</html>
When i ran this program except the header , no data is being displayed , could you please let me know what might the cause for it ??
You have an extra # in $("##example").dataTable({

Loading script from .js file

I'm trying to load a .htm template from .js file. But there is a script present in .htm file which gets triggers when the template is loaded and things are smooth.
Here how the template looks. testing.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>http://stackoverflow.com/questions/6946559/jqgrid-please-help</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#example').dataTable({
"bProcessing": true,
"sAjaxSource": '/Home/GetData',
"sScrollY": "400px",
"sScrollX": "200px",
"bPaginate": false
});
});
</script>
</head>
<div id="dynamic">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<tr>
<th width="20%">Date</th>
<th width="25%">Name</th>
<th width="25%">ProposalID</th>
<th width="25%">Time</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</html>
Here is the .js file which loads the template.
var iTabs = function () {
return {
Init: function () {
var placeholder = $("#testtab");
placeholder.setTemplateURL("/Templates/Home/testing.htm");
placeholder.load("/Templates/Home/testing.htm");
}
}
} ();
But, now i want to execute the .htm script in .js file i.e after loading the template.
If i run only a part of script i.e
$('#example').dataTable({
"bProcessing": true,
"sAjaxSource": '/Home/GetData',
"sScrollY": "400px",
"sScrollX": "200px",
"bPaginate": false
});
in .js file, it wont work. Is it possible to run this script in .js file?. if so how?
Try to run that js code using the callback of the load
Like this :
placeholder.load("/Templates/Home/rpt.htm", function() {
$('#example').dataTable({
"bProcessing": true,
"sAjaxSource": '/Home/GetData',
"sScrollY": "400px",
"sScrollX": "200px",
"bPaginate": false
});
});
For more info , refer to the jQuery load docs

Categories

Resources