Can not fill DataTable with json data - java

I am creating java web application. For display data in table i am using datatable plugin. Here is my function which send post to servlet and get json data. When i check returned json i see everything okay but i can not display this data in my datatable.
What is json return:
{"data":[{"id":32,"fullName":"Murad Heydarov Cefer","name":"Murad","surname":"Heydarov","middleName":"Cefer","department_name":"Proqramlasdirma","startedToWork":"11/03/2017","note":"must go this week"}]}
$(document).ready(function () {
$('#example').DataTable({
"ajax": {
"url": "../employer/list",
"type": "POST",
"datatype": "json",
"success": function (data) {
console.log(data);
}
},
"columnDefs": [{
"searchable": false,
"orderable": false,
"targets": 0
}],
"order": [[1, 'asc']],
"columns": [
{"data": null},
{"data": "fullName"},
{"data": "name"},
{"data": "surname"},
{"data": "middleName"},
{"data": "department_name"},
{"data": "startedToWork"},
{"data": "note"},
{"data": "id"}
]
});
});
Here is my Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
int worker_id;
String str = (String) session.getAttribute("SID");
SimpleDateFormat tsdf = null;
if (u.module(request).equals("employer"))
{
Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
switch (u.view(request))
{
case "list":
JsonElement workerListJson = gson.toJsonTree(workerAction.Connect());
jsonObject.add("data", workerListJson);
out.println(jsonObject.toString());
break;
}
}
}
Jsp file:
<table id="example" class="ui celled table" cellspacing="0" width="100%">
<thead>
<tr>
<th>#</th>
<th>full name</th>
<th>department name</th>
<th>started to work</th>
<th>days remain</th>
<th>period</th>
<th>times</th>
<th>note</th>
<th>action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>#</th>
<th>full name</th>
<th>department name</th>
<th>started to work</th>
<th>days remain</th>
<th>period</th>
<th>times</th>
<th>note</th>
<th>action</th>
</tr>
</tfoot>

Related

How to add parameterized fragment in form recursively in Thymeleaf?

I have a data structure, it contains primitive and complex values.
public class Topic{
private String topicUrl = "";
private String key = "";
private String name = "";
private String value = "";
private String type;//RECORD/ARRAY/ENUM/PRIMITIVE
private List<String> enumValues = new ArrayList<>();
private List<Topic> fieldList = new ArrayList<>();
//getters setters
//isEnum()
//isPrimitive()
//isRecord()
}
And I have created thymeleaf frontend to submit Topic objects. only value fields of primitive objects can be edited on frontend. example object is like
Before submit as JSON:
{
"topicUrl": "url",
"key": "",
"name": "object1",
"value": "",
"type": "RECORD",
"fieldList": [
{
"topicUrl": "",
"key": "",
"name": "object1.1",
"value": "",
"type": "INT",
"fieldList": []
},
{
"topicUrl": "",
"key": "",
"name": "object1.2",
"value": "",
"type": "RECORD",
"fieldList": [
{
"topicUrl": "",
"key": "",
"name": "object1.2.1",
"value": "",
"type": "INT",
"fieldList": []
}]
}]
}
After submit as JSON:
{
"topicUrl" : "url",
"key" : "",
"name" : "object1",
"value" : "",
"type" :"RECORD",
"fieldList":[{
"topicUrl" : "",
"key" : "",
"name" : "object1.1",
"value" : "11",
"type" :"INT",
"fieldList":[]
},{
"topicUrl" : "",
"key" : "",
"name" : "object1.2",
"value" : "",
"type" :"RECORD",
"fieldList":[{
"topicUrl" : "",
"key" : "",
"name" : "object1.2.1",
"value" : "121",
"type" :"INT",
"fieldList":[]
}]
}]}
Form page
<form th:action="#{/writeTopic}" th:object="${selectedTopic}" method="post" class="form-horizontal">
<fieldset>
<input type="submit" class="btn btn-primary" th:value="Write"></input>
<table class="table table-striped table-bordered">
<tbody>
<tr>
<td th:text="TopicUrl"></td>
<td>
<input readonly th:field="*{topicUrl}" class="form-control form-control-lg"/>
</td>
</tr>
<tr>
<td th:text="Key"></td>
<td>
<input th:field="*{key}" class="form-control form-control-lg"/>
</td>
</tr>
</table>
<div th:replace="fragments/topicFieldsTable :: topicFieldsTable(topic=${selectedTopic})"></div>
</fieldset>
</form>
Every Topic object contain Topic elements in fieldList if type is "RECORD". so that I have created topicFieldsTable.html fragment for recursion
<table th:fragment="topicFieldsTable(topic)" class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th scope="col" th:text="${topic.className}"></th>
<th scope="col">Type</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr th:each="field, itemStat : ${topic.fieldList}">
<td>
<!--field.name-->
<label th:text="${field.name}">Name</label>
</td>
<td>
<!--field.type-->
<label th:text="${field.type}">Type</label>
</td>
<td th:if="${field.isEnum()}">
<select class="form-control form-control-lg">
<option th:each="eval : ${field.enumValues}"
th:value="${eval}"
th:text="${eval}">Value</option>
</select>
</td>
<td th:if="${field.isRecord()}">
<div th:replace="fragments/topicFieldsTable :: topicFieldsTable(topic=${field})"></div>
</td>
<td th:if="${field.isPrimitive()}">
<!--field.value-->
<input name="value" th:name="${field.name}" th:value="${field.value}" class="form-control form-control-lg"/>
</td>
</tr>
</tbody>
</table>
Additionally I couldn't assign fields with th:field in fragment.
Do you have any idea?

Json data how to pass in to DataTable using Jsp

i am creating simple crud system using jsp. data passing through json format i tested through console it is passing well but data is not display on the datatable.i don't why. i wrote what i tried so far.
Table
<table id="tbl-projects" class="table table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
jQuery
<script>
get_all()
function get_all()
{
$('#tbl-projects').dataTable().fnDestroy();
$('#etbl-projects').DataTable().ajax.reload();
$.ajax({
url : "all_project.jsp",
type : "GET",
dataType : "JSON",
success:function(data)
{
alert(data.course);
$('#tbl-projects').dataTable({
"aaData": data,
"scrollX": true,
"aoColumns": [
{"sTitle": "StudentName", "mData": "name"},
{"sTitle": "Course", "mData": "course"},
{"sTitle": "Fee", "mData": "fee"},
{
"sTitle": "Edit",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success" onclick="get_project_details(' + mData + ')">Edit</button>';
}
},
{
"sTitle": "Delete",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-primary" onclick="Remove_details(' + mData + ')">Delete</button>';
}
}
]
});
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
</script>
all_project.jsp
Jsp Page
<%#page import="org.json.simple.JSONObject"%>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%
Connection con;
PreparedStatement pst;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
String query="select * from records";
Statement stmt=con.createStatement();
rs=stmt.executeQuery(query);
while(rs.next())
{
String id =rs.getString("id");
String name =rs.getString("name");
String course =rs.getString("course");
String fee =rs.getString("fee");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("course", course);
json.put("fee", fee);
json.put("id", id);
out.print(json);
out.flush();
}
%>
i have tested through the console result. screen shot below
{"fee":"10000","name":"john","course":"java","id":"1"}{"fee":"7000","name":"Raja","course":"C#","id":"2"}{"fee":"2323","name":"sad","course":"asd","id":"3"}{"fee":"12000","name":"Nishan","course":"Jsp","id":"4"}
i have attached the Datatable image below
enter image description here
Your response in JSON format is invalid (missing comas between object).
Use org.json.simple.JSONArray to create a list of objects, for example:
<%#page import="org.json.simple.JSONArray"%>
...
JSONArray list = new JSONArray();
while(rs.next())
{
String id = rs.getString("id");
String name = rs.getString("name");
String course = rs.getString("course");
String fee = rs.getString("fee");
JSONObject obj = new JSONObject();
obj.put("name", name);
obj.put("course", course);
obj.put("fee", fee);
obj.put("id", id);
list.put(obj);
}
out.print(list.toJSONString());
out.flush();

Datatable not showing in Spring MVC data

I am trying to get the data from Spring MVC and show it in datatables.
On a webpage, the datatable is showing processing.
I tried to console out my value and in console my arrays are showing.
Can anyone help out?
JSP table:
<div>
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th class="col-sm-1">Department Id</th>
<th class="col-sm-3">Department Name</th>
</tr>
</thead>
</table>
</div>
JavaScript code:
<script>
$(document).ready(function () {
table = $("#myTable").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": false, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/com-employee-record/department/listDataTable.json",
"type": "POST",
"datatype": "json",
"success" : function(data, i){
console.log(data[0]);
}
},
"columns" : [
{ "data": "department_id"},
{ "data": "department_name"}
]
});
});
</script>
Controller code:
#RequestMapping(value = "/listDataTable.json", method = RequestMethod.POST, headers = "Accept=application/json")
#ResponseBody
public List<Department> dataTable(HttpServletRequest request) {
return departmentService.getDepartments();
}
Here is what my console is showing:
{department_id: 1, department_name: "Information Technology"}
I think you need to use the:
"dataSrc": ""
setting, because your API response does not have a top level js property called "data".
The code below is working.
<script src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/datatables.min.js"></script>
<script>
$(document).ready(function() {
$('#example3').DataTable({
"ajax": {
"type": "GET",
"url": 'https://jsonplaceholder.typicode.com/todos',
"contentType": 'application/json; charset=utf-8',
"dataSrc": "",
},
"columns": [
{
"data": "id"
},
{
"data": "title"
}
]
});
});
</script>
<table id="example3" class="display" style="width:100%">
</table>
Everything seems to be fine just change ajax part of your code to this
"ajax": {
"url": "/com-employee-record/department/listDataTable.json",
"type": "POST",
"contentType": "application/json",
"dataSrc" : "[]"
},
dataSrc was missing in your code. No need to have success block.

Json serialize to java pojo with nested List<pojo> property

Below is my code attempt to post an Json serialize object (java pojo having list of other pojos) with JQuery Ajax call to Spring MVC controller.
Getting Bad request error from server.
When the modalForm data is removed from the Json object the MainPojo data received correctly at server side.
Html Code
Fisrt form
-------------
<form id="mainForm">
.....
</form>
Form in the modal
-----------------
<form id="modelform" ..>
<div id="row">
<input type="text" id="subject" />
<input type="text" id="max" />
<input type="text" id="min" />
</div>
<div id="row">
<input type="text" id="subject" />
<input type="text" id="max" />
<input type="text" id="min" />
</div>
.............
</form>}
Jquery
var mainObject = $('#mainForm').serializeObject();
var modelObject = $('#modelform').serializeObject();
mainObject.marks = modelObject;
Json ( Expected)
{
"name": "Some Name",
"age": "10",
"marks": [
{
"subject": "maths",
"max": "20",
"min":"12"
},
{
"subject": "english",
"max": "20",
"min":"12",
}
]
}
Json (actual output with the above code)
{
"name": "Some Name",
"age": "10",
"marks": [
{
"subject": "maths",
"subject": "english"
},
{
"max": "20",
"max":"20",
},
{
"min": "12",
"min":"12"
}
]
}
//Ajax call
$.ajax({
url: '/save',
type: 'POST',
contentType: 'application/json',
mimeType: 'application/json',
data : JSON.stringify(mainObject),
dataType: 'json',
success: function(data) {
alert(data.msg);
},
error:function (xhr, ajaxOptions, thrownError) {
alert('Technical error occured');
}
});
Java Pojo's
public class MainPojo {
private String name;
private String age;
private Lists<marks>
..................
}
public class ModelPojo {
private String subject;
private String maxMarks;
private String minMarks;
.....................
}
Controller Method
#RequestMapping(value = "save", headers = "Accept=application/json",
method = RequestMethod.POST)
public #ResponseBody String save(#RequestBody final MainPojo mainPojo) {
}
Please help me to identify the problem.
Thank You.
Modify html text like this
<form id="mainForm">
<input name="name" type="text" value="Some Name">
<input name="age" type="text" value="20">
</form>
<form class="modelform">
<input type="text" value="subject" name="subject"/>
<input type="text" value="max" name="max"/>
<input type="text" value="min" name="min"/>
</form>
<form class="modelform">
<input type="text" value="subject" name="subject" />
<input type="text" value="max" name="max"/>
<input type="text" value="min" name="min"/>
</form>
Then write javascript code to assign object value
<script>
var mainObject = $('#mainForm').serializeObject();
var modelObject = [];
$('.modelform').each(function(o){
modelObject.push($(this).serializeObject());
})
mainObject.marks = modelObject;
</script>
i have
#RequestMapping(value = "/save", method = RequestMethod.POST)
public #ResponseBody
MyEvent saveOrganization(#RequestBody Organization organization) {
return new MyEvent('save',organization);
}
y your mvc-servlets.xml
<context:component-scan base-package="com.jrey.project.controllers" />
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
my jquery post
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
<script>
$(document)
.ready(
function() {
$('.submit', '#form')
.click(
function() {
var data = JSON
.stringify($('#form')
.serializeObject());
console.log(data);
$
.ajax({
type : "POST",
url : '${pageContext.request.contextPath}/controller/organization',
data : data,
dataType : 'json',
contentType : 'application/json;charset=UTF-8',
success : function(data) {
$(
'<div>'
+ data.message
+ '</div>')
.dialog(
{
title : 'Organizacion',
modal : true,
buttons : {
'Aceptar' : function() {
document.location.href = data.location;
}
}
}
);
},
});
});
});

jQuery+Spring remove from database

I have a project using Spring and i need to create admin page using jQuery. I have a table with all users and i have a button "delete". When i click it user should be deleted from the database. Without script everything works fine but with script i can't figure out how do i make user deleted from database and how to send user login to controller. I could only remove row from table, but when i refresh the page user is still there.
Could anyone please help me how to delete user from db within script?
Table
<table id="userBase" class="data" border="1" width="100%" cellpadding="2" cellspacing="4">
<tr>
<th>Login</th>
<th>First Name</th>
<th>Last Name</th>
<th>Birthday</th>
<th>Role</th>
<th>Actions</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.login}</td>
<td>${user.firstname}</td>
<td>${user.lastname}</td>
<td>${user.birthday}</td>
<td><c:if test="${user.roleid==1}">Admin</c:if>
<c:if test="${user.roleid==2}">User</c:if></td>
<td>Edit
<a class="confirm" href="delete/${user.login}">Delete</a></td>
</tr>
</c:forEach>
</table>
Controller without script(it's commented now, but it works fine)
#RequestMapping("/delete/{userLogin}")
public String deleteUser(#PathVariable("userLogin") String userLogin) {
userService.remove(userService.findByLogin(userLogin));
return "redirect:/welcome";
}
Controller for script
#Controller
public class SpringController {
#Autowired
private UserService userService;
#RequestMapping(value = "/delete/{userLogin}", method = RequestMethod.POST)
#ResponseBody
public boolean updateUser(#RequestParam("userLogin") String userLogin) {
userService.remove(userService.findByLogin(userLogin));
return true;
}
}
Script
<script>
$(document).ready(function() {
$("#userBase .confirm").on("click",function() {
var conBox = confirm("Are you sure ?");
if(conBox){
var tr = $(this).closest('tr');
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();
});
} else {
$(this).dialog("close");
}
});
});
</script>
Here's what worked for me:
Table (check "Delete" link)
<table id="userBase" class="data" border="1" width="100%" cellpadding="2" cellspacing="4">
<tr>
<th>Login</th>
<th>First Name</th>
<th>Last Name</th>
<th>Birthday</th>
<th>Role</th>
<th>Actions</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.login}</td>
<td>${user.firstname}</td>
<td>${user.lastname}</td>
<td>${user.birthday}</td>
<td><c:if test="${user.roleid==1}">Admin</c:if>
<c:if test="${user.roleid==2}">User</c:if></td>
<td>Edit
Delete
</tr>
</c:forEach>
</table>
Controller
#RequestMapping(value="/delete/{userLogin}", method=RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void deleteUser(#PathVariable String userLogin) {
userService.remove(userService.findByLogin(userLogin));
}
Script
<script>
$(document).ready(function() {
var deleteLink = $("a:contains('Delete')");
$(deleteLink).click(function(event) {
var conBox = confirm("Are you sure ?");
if(conBox){
$.ajax({
url: $(event.target).attr("href"),
type: "DELETE",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function() {
var tr = $(event.target).closest("tr");
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();})
}
});
} else {
event.preventDefault();
}
event.preventDefault();
});
});
</script>
On your code, you are not calling the needed url to call the handler method that will delete the user. I assume you want to do this using ajax? it would also help if you can add your markup.
What you can do is(for now since your question and your code seems pretty vague)
$(document).ready(function() {
$("#userBase .confirm").on("click",function() {
var conBox = confirm("Are you sure ?");
var userLogin = "sampleOnly" //maybe somewhere in your html you have this
var url = "mycontroller/delete/"+userLogin //A rough guess for now
if(conBox){
$.post(url+userLogin,function(e){
var tr = $(this).closest('tr');
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();
})
});
} else {
$(this).dialog("close");
}
});
});
If you want to send data using jQuery, I'd suggest using AJAX with REST. Here's how I'd do it:
#RequestMapping(value="delete.json", method=RequestMethod.DELETE, produces="application/json")
#ResponseBody
public Boolean deleteAjaxMultiple(#RequestBody String[] gotten)
{
for (String login : gotten)
userService.remove(userService.findByLogin(login));
return true;
}
This controller handles JSON requests, in this case an array of logins. Then you'll just have to call it from JavaScript like this:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: '/delete.json', //or whatever url works for you
type: 'DELETE',
data: JSON.stringify(arr), //arr is an array of logins you want to delete
success: function(data) {
location.reload(true); //or do whatever you want on success
}
});
You need to set up Jackson for this. For more info see this and this.

Categories