Unable to link a column in datatables - java

<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Populating JSP</title>
<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.0/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.0/css/jquery.dataTables.css" />
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.css" />
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>salary</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
$(document).ready(function() {
$('#example').dataTable( {
serverSide: true,
"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
$('td:eq(2)', nRow).html('<a href="http://www.google.com' + aData[2] + '">' +
aData[2] + '</a>');
return nRow;
},
ajax : {
url: 'hello/data1',
dataType:'json',
type: 'POST'
}
}
);
});
</script>
</body>
</html>
I have 2 coulmns, ID and Salary. I am linking the salary to google.com, for that I am using fnRowCallback function. But that doesn't seem to work. Where do you think I am going wrong. The jsp is shown above.

Use custom column definition columnDefs to alter column rendering.
$('#example').dataTable( {
serverSide: true,
"aoColumnDefs" : [
{
"mData": "name",
"sClass": "dataTable-user-list-name",
"fnRender": function (oObj) {
return '<a href="/#/' + oObj.aData['detailsUrl'] + '">oObj.aData['name']<a>'
}],
ajax : {
url: 'hello/data1',
dataType:'json',
type: 'POST'
}
}

Related

DataTables warning: table id=example - Ajax error

I am using jquery Datatables and I am getting this error: DataTables warning: table id=example - Ajax error. This is MVC app. Data is from MSQL database. have no error on chrome's console. Maybe it is a syntax problem?
Here is my .jsp file:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
<script>
function confirmDelete(id) {
if (confirm("Are you sure to delete this cost?")) {
window.location.href = "/cost/delete/" + id;
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="../../resources/js/datatable.js"></script>
</head>
<body>
<table id="example" class="display" style="width:80%">
<thead>
<tr>
<th>ID</th>
<th>Date</th>
<th>MPK</th>
<th>Account</th>
<th>Client</th>
<th>Amount</th>
<th>Description</th>
<th>Payment</th>
<th>Invoice Number</th>
<th>Department</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<c:forEach var="costs" items="${allcosts}">
<tr>
<td>${costs.id}</td>
<td>${costs.salesDate.toString()}</td>
<td>${costs.mpk.code}</td>
<td>${costs.account.code}</td>
<td>${costs.client.name}</td>
<td>${costs.amount.toString()}</td>
<td>${costs.description.toString()}</td>
<td>${costs.payment.type}</td>
<td>${costs.invoiceNumber.toString()}</td>
<td>${costs.department.name}</td>
<td>Delete</td>
<td>Edit</td>
</tr>
</c:forEach>
</tbody>
</table>
<spring:url value="/report/?type=xls" var="xlsURL"/>
Download Excel
</body>
</html>
Here is my .js file:
$(document).ready(function () {
$('#example').DataTable({
"processing": true,
"serverSide": true,
"pageLength": 5,
"ajax": {
"url": "/cost/all",
"columns": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
{"data": "Delete"},
{"data": "Edit"}
]
} });
});
How can I solve this problem? I am stuck.
Use the following initialization code instead:
$(document).ready(function () {
$('#example').DataTable({
pageLength: 5
});
});

JSON data is not visible in jqgrid

I am quite new with JSON. I want to show the java object data as JSON data. I have done some code but it is showing only the grid, not the grid data.
My jsp page looks like this:
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Jeeni Software - jQuery Ajax Data Grid Example</title>
<c:set var="baseURL" value="${pageContext.request.contextPath}"/>
<script type="text/javascript" src="${baseURL}/js/jquery.min.js"></script>
<script type="text/javascript" src="${baseURL}/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="${baseURL}/js/jquery-ui.min.js"></script>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/redmond/jquery-ui.css">
<link rel="stylesheet" href="css/redmond/jquery.ui.theme.css">
<link rel="stylesheet" href="css/jqgrid/ui.jqgrid.css">
<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> -->
<!-- <script src="http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script> -->
<!-- <script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script> -->
<!-- <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script> -->
<script>
$(document).ready(function() {
setupGrid();
attachSendDataEvent();
attachDeleteButton();
});
function attachSendDataEvent(){
$("#sendData").click(function(){
var data = "firstName=" + $("#firstName").val() + "&" +
"lastName=" + $("#lastName").val() + "&" +
"address=" + $("#address").val() + "&" +
"postcode=" + $("#postcode").val();
$.post("data/person/put",
data,
dataSentOK
);
});
return false;
}
function attachDeleteButton(){
$("#deleteBtn").click(function(){
var grid = jQuery("#dataTable").jqGrid();
var rowNum = grid.getGridParam('selrow');
if(rowNum){
var person = grid.getRowData(rowNum);
var data = "perId=" + person.id;
$.post("data/person/delete",
data,
dataSentOK
);
}
});
}
function dataSentOK(){
jQuery("#dataTable").jqGrid().trigger("reloadGrid");
}
function setupGrid(){
jQuery("#dataTable").jqGrid({
url: "data/person/get",
datatype: "json",
loadonce : false,
jsonReader: {root : "rows", repeatitems: false, id: "id"},
colNames:['ID','First Name','Last Name', 'Address', 'Postcode'],
colModel:[
{name:'id',index:'id', width:20},
{name:'firstName',index:'firstName', width:100},
{name:'lastName',index:'lastName', width:100},
{name:'address',index:'address', width:380},
{name:'postcode',index:'postcode', width:100}
],
rowNum:4,
rowList:[5,10,20,30],
height:200,
pager: "#pagingDiv",
viewrecords: true,
caption: "Names and Addresses"
}).navGrid('#pager', {edit:false,add:false,del:false, search: false});
}
</script>
</head>
<body>
<div class="centreDiv">
<div class="heading"><h1>Jeeni Software - jQuery Ajax Data Grid Example</h1></div>
<div>
<div style="height:170px;">
<div class="form">
<div class="padding">
<label>First Name:</label> <input id="firstName"/><br/>
<label>Last Name:</label> <input id="lastName"/><br/>
<label>Address:</label> <input id="address" size="40"><br/>
<label>Postcode:</label> <input id="postcode"/><br/>
<button id="sendData">Send</button>
</div>
</div>
</div>
<!-- jqGrid will be injected into this DIV-->
<h2>jqGrid Data Table</h2>
<div>
<table id="dataTable"></table>
<div id="pagingDiv"></div>
<button id="deleteBtn">Delete Row</button>
</div>
</div>
</div>
</body>
</html>
And the spring controller like this:
#RequestMapping(value="get", method = RequestMethod.GET)
#ResponseBody
public JqGridData<Person> getPeople(#RequestParam("page") int page,
#RequestParam("rows") int rows,
#RequestParam("sidx") String sortColumnId,
#RequestParam("sord") String sortDirection){
int totalNumberOfPages = GridUtils.getTotalNumberOfPages(people, rows);
int currentPageNumber = GridUtils.getCurrentPageNumber(people, page, rows);
int totalNumberOfRecords = people.size();
List<Person> pageData = GridUtils.getDataForPage(people, page, rows);
JqGridData<Person> gridData = new JqGridData<Person>(totalNumberOfPages, currentPageNumber, totalNumberOfRecords, pageData);
return gridData;
}
Can anybody please tell me what's wrong with this code?

Kendo UI Simple Grid

I am struggling with using the JSP wrapper in Kendo UI.
I checked their forum and found nothing. I checked stackoverflow and found nothing. I read through the APIs but could not find an answer to my issue.
The call to
url: "CustomerAjaxServlet?str=The R",
returns the following json object:
[
{"id":0,"customerId":"RO113","name":"The Robe Gallery Inc."},
{"id":1,"customerId":"TH204","name":"The Robe Collection"}
]
The grid is being rendered with the correct column headers and the paging is coming back
1 of 10 121 Items. But there is no data.
121 is the character count of the json object.
If I change the call the ajax servlet, the number of items changes too along with the 1 of ...
<%# page language="java" %>
<%# taglib uri="/WEB-INF/tlds/esc.tld" prefix="esc" %>
<%# taglib uri="/WEB-INF/tlds/struts-html.tld" prefix="html" %>
<%# taglib uri="/WEB-INF/tlds/struts-bean.tld" prefix="bean" %>
<%# taglib uri="/WEB-INF/tlds/struts-logic.tld" prefix="logic" %>
<%#taglib prefix="kendo" uri="http://www.kendoui.com/jsp/tags"%>
<%# page import="org.apache.struts.taglib.TagUtils" %>
<% SessionContext context = SessionContext.getSessionContext(request); %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Detail template</title>
<meta http-equiv="Content-Type" content='text/html; charset=us-ascii'>
<meta name='author' content=Test'>
<link href="common/js/kendo/examples/content/shared/styles/examples-offline.css" rel="stylesheet">
<link href="common/js/kendo/styles/kendo.common.min.css" rel="stylesheet">
<link href="common/js/kendo/styles/kendo.default.min.css" rel="stylesheet">
<script src="common/js/kendo/js/jquery.min.js"></script>
<script src="common/js/kendo/js/kendo.web.min.js"></script>
<script src="common/js/kendo/content/shared/js/console.js"></script>
</head>
<body>
<a class="offline-button" href="../index.html">Back</a>
<div id="example" class="k-content">
<div id="grid"></div>
<script type="text/x-kendo-template" id="template">
<div class="tabstrip">
<div>
<div class='customer-details'>
<ul>
<li><label>id:</label>#= id #</li>
<li><label>name:</label>#= name #</li>
<li><label>customerId:</label>#= customerId #</li>
</ul>
</div>
</div>
</div>
</script>
<script>
$(document).ready(function() {
var element = $("#grid").kendoGrid({
dataSource: {
transport: {
read: function(options) {
$.ajax( {
url: "CustomerAjaxServlet?str=The R",
data: options.data, success: function(result) {
options.success(result);
//alert(result);
}
});
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true
},
height: 450,
sortable: true,
pageable: true,
dataBound: function() {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "id",
title: "Id"
},
{
field: "name",
title: "Name"
},
{
field: "customerId",
title: "Customer Id"
}
]
});
});
</script>
<style scoped="scoped">
.customer-details ul
{
list-style:none;
font-style:italic;
margin-bottom: 20px;
}
.customer-details label
{
display:inline-block;
width:90px;
font-style:normal;
font-weight:bold;
}
</style>
</div>
</body>
</html>
Your code runs fine. Did you check the contentType of the json object returned? It should be "application/json".
I run your code with the following CustomerAjaxServlet
<%# page contentType="application/json;charset=UTF-8" language="java" %>
<%
out.println("[" +
"{\"id\":0,\"customerId\":\"RO113\",\"name\":\"The Robe Gallery Inc.\"}," +
"{\"id\":1,\"customerId\":\"TH204\",\"name\":\"The Robe Collection\"}" +
"]");
%>

Edit link of a table of each row will send the primary key of the row to controller

Hi i am new in jsp and Spring. I have a table of employee information. I want to add a edit link in each row and an edit link will be click it will send the primary key of the row to the controller. When i click the edit link it display the error "The request sent by the client was syntactically incorrect ()."
This page display the table
employeeList.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee List</title>
</head>
<body>
<div align="center">
<h1 align="center">Employee List</h1>
<table align="center" border="1">
<tr><th>Pk</th><th>Employee Name</th><th>Employee email</th><th>Address</th><th>Manager Id</th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="employeeList" items="${list}">
<tr>
<td><c:out value="${employeeList.id}"/></td>
<td><c:out value="${employeeList.name}"/> </td>
<td><c:out value="${employeeList.email}"/> </td>
<td><c:out value="${employeeList.address}"/></td>
<td><c:out value="${employeeList.managerId}"/></td>
<td><a href="editEmployee.htm?id=${id}" >Edit</a></td>
<td><a href="deleteEmployee.htm?id=${id}" >Delete</a></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
my controller code is
#RequestMapping(value="/editEmployee.htm")
public String editEmployee(#RequestParam("id") int id,ModelMap model){
try {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "editEmployee";
} catch (Exception ex) {
return "index";
}
}
editEmployee.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
}
</style>
</head>
<body>
Edit Employee<br>
</body>
</html>
How i can solve this problem.
Change your jsp to something like this
<c:url var="editUrl" value="/editEmployee.htm" />
<a href="${editUrl}?id=${employeeList.id}">
Edit
</a>
<c:url var="deleteUrl" value="/deleteEmployee.htm" />
<a href="${deleteUrl}?id=${employeeList.id}">
Delete
</a
#RequestMapping(value="/editEmployee.htm") - wrong
#RequestMapping(value="/editEmployee/{id}")
public String editEmployee(#PathVariable int id,ModelMap model){
try {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "editEmployee";
} catch (Exception ex) {
return "index";
}
}
and also a href="editEmployee.htm?id=${id}
this should be something like a href="editEmployee/${id}

Use JQuery SWF plugin in JSP

I used an example script of how to load an SWF file with the JQuery SWF plugin (http://jquery.thewikies.com/swfobject/examples). I am trying to get the plugin to work in a JSP. It appears to work in FireFox and Chrome but not in IE8.
Can anyone see any obvious issues? Thanks in advance.
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
</head>
<script type="text/javascript" src="js/jquery.swfobject.1-1-1.js"></script>
<body>
<script type="text/javascript">
var bar_chart = $.flash.create (
{
swf: 'flash/open-flash-chart.swf',
width: 350,
height: 260,
wmode: 'transparent',
play: true,
flashvars: {
"get-data": "getChart1Data"
}
}
);
function getChart1Data()
{
return JSON.stringify(${chart1Data});
};
function ofc_ready()
{
/**/
};
$(document).ready(
function() {
$('#bar_chart').html(bar_chart);
}
);
</script>
<tr>
<td colspan="2">
<table>
<tr>
<td>
<div id="bar_chart"></div>
</td>
</tr>
</table>
</td>
</tr>
</body>
</html>
Your HTML is syntactically invalid. The browser behaviour is unpredictable.
This one is syntactically valid. Give it a try.
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert your title</title>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/jquery.swfobject.1-1-1.js"></script>
<script type="text/javascript">
var bar_chart = $.flash.create ({
swf: 'flash/open-flash-chart.swf',
width: 350,
height: 260,
wmode: 'transparent',
play: true,
flashvars: {
"get-data": "getChart1Data"
}
});
function getChart1Data() {
return JSON.stringify(${chart1Data});
}
function ofc_ready() {
/**/
}
$(document).ready(function() {
$('#bar_chart').html(bar_chart);
});
</script>
</head>
<body>
<div id="bar_chart"></div>
</body>
</html>
PS: I removed the table since it's incomplete and only adds noise to the demo.
All you have to do is change your swfobject version to latest SWFObject 2.2
<script type="text/javascript" src="js/jquery.swfobject.1-1-1.js"></script>
This will fix ie issue
try
flashMovie = null;
$(document).ready(
function () {
flashMovie = $('#bar_chart');
flashMovie.flash(
{
swf: 'flash/open-flash-chart.swf',
width: 350,
height: 260,
wmode: 'transparent',
play: true,
flashvars: { "get-data": "getChart1Data" }
}
);
}
);
function getChart1Data() { return JSON.stringify(${chart1Data}); };

Categories

Resources