Not displaying JSON data in Jquery datatable - java

I am trying to display sample data from my Java controller into the table, however, it is not rendering the data nor displaying any error messages. For the time being, I am trying to display simple mock data in JSON format...However, the table is not displaying any data nor any error messages..
I am using JSP, AngualrJS and jquery for front end, Java for backend..
This is my JSP Page table:
<table class="table table-striped table-bordered dt-responsive nowrap" id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
</tr>
</thead>
</table
This is my JSP page:
$.ajax({
url:"/home/review/",
success:function(data) {
var table = $('#myTable').DataTable( {
"data": data,
dom: "Bfrtip",
"iDisplayLength": 15,
"lengthChange": false,
"ordering": true,
"info": false,
'columnDefs': [
{
'targets': 1,
'orderable': false,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
{ "data": "id", "defaultContent": "" },
{ "data": "status", "defaultContent": ""}
],
});
}
});
This is my angularJS Controller:
angular.module('myApp').controller('HomeController', ['DTOptionsBuilder', 'DTColumnBuilder','HomeService', '$scope', function(DTOptionsBuilder, DTColumnBuilder, HomeService, $scope) {
var test_URL = '/home/review/';
var self = $scope;
var vm = this;
vm.dtOptions = HomeService.fetchList();
console.log(vm.dtOptions);
}]);
My angularJS service:
angular.module('myApp').factory(HomeService', ['$http', '$q', function($http, $q){
var URL= '/home/review/';
var factory = {
fetchList: fetchList
};
return factory;
function fetchList() {
var deferred = $q.defer();
$http.get(URL)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching List');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}]);
This is my Java backend controller:
#RequestMapping(value = "/review/", method = RequestMethod.GET)
public String geList() throws JSONException {
logger.info("List All Controller");
System.out.println("Fetching All list...");
JSONArray resultarray = new JSONArray();
String resultString = "";
JSONObject result = new JSONObject();
result.put("id","1234");
result.put("status", "New");
resultarray.put(result);
resultString = resultarray.toString(4);
System.out.println(resultString);
return resultString;
}

Try JSON.parse() for your data, while passing to the DataTable.

Related

datatables Load data exception

I've got the JSON data behind the scenes, that's it
[{"aid":100000,"name":"JYCM201609010250","rtsp":"947|100000|3750","statuz":"1","updateTime":"2017-05-31"},{"aid":100001,"name":"gui","rtsp":"947|100000|3750","statuz":"0","updateTime":"2017-05-31"}]
Background and foreground code are as follows
#Autowired
private MediaImpl media;
#ResponseBody
#RequestMapping(value = "/media",method = RequestMethod.GET)
public List<Media> MediaAll(){
System.out.println("------------------------------------------------------");
return media.findAll();
}
JS code is as follows
<script>
$(document).ready(function () {
$('#table_id_example').DataTable({
"iDisplayLength": 10,
"bLengthChange": false,
"ajax": {
"url": "/media",
"dataType": "json",
"success": function (json) {
console.log(json)
}
},
"columns": [
{
"data": 'aid'
},
{
"data": 'name'
},
{
"data": 'rtsp'
},
{
"data": 'statuz'
},
{
"data": 'updateTime'
}
]
});
});
html code is as follows
The console code
VM178:10 (2) [{…}, {…}]0: {aid: 100000, name: "JYCM201609010250", rtsp: "947|100000|3750", statuz: "1", updateTime: "2017-05-31"}1: {aid: 100001, name: "gui", rtsp: "947|100000|3750", statuz: "0", updateTime: "2017-05-31"}length: 2__proto__: Array(0)
There is no error in the front-end console, and no errors in the back end.But the data is not available
There are a couple of problems here. The first is that datatables expects data in a data element of the json response, such as:
{
data: [{"aid":100000,"name":"JYCM201609010250","rtsp":"947|100000|3750","statuz":"1","updateTime":"2017-05-31"},{"aid":100001,"name":"gui","rtsp":"947|100000|3750","statuz":"0","updateTime":"2017-05-31"}]
}
You should be able to use ajaxSrc: "" on your DataTable settings.
The second problem is with your ajax settings. DataTables states you can not supply the success callback in the ajax settings as it uses this internally.
Documentation on both of these issues:
https://datatables.net/reference/option/ajax
Assuming you are using DataTables 1.10.x

How to connect data from Oracle database to Kendo Grid using Java?

I could able to create a grid using local data. I want to know how to get data from Oracle database to display as a Kendo Grid?
How to modify "read" function in datasource to get data?
Servlet
public class TeacherListPageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
ArrayList<MessageObjects> listArr;
OracleConnection oraconn= new OracleConnection();
listArr= oraconn.teacherDetails();
System.out.println("In teacher servlet \n" );
if(!listArr.isEmpty()){
Gson gson= new Gson();
String json=gson.toJson(listArr);
System.out.println("In list");
System.out.println(json);
request.setAttribute("list",json);
request.getRequestDispatcher("Grid.jsp").forward(request, response);
//response.sendRedirect("Grid.jsp");
}
else
{
System.out.println("list is empty");
}
}
}
listArr= oraconn.teacherDetails(); will call OracleConnection.java
OracleConnection
public ArrayList teacherDetails()
{
ArrayList<MessageObjects> list= new ArrayList<MessageObjects>();
ArrayList<String> list1= new ArrayList<>();
MessageObjects obj= new MessageObjects();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","STUDENT_DB","Aishwarya11");
Statement statement=con.createStatement();
ResultSet rs= statement.executeQuery("select * from TEACHERS_DETAILS");
while(rs.next()) {
obj.setTid(rs.getString(1));
obj.setName(rs.getString(2));
obj.setGender(rs.getString(3));
obj.setDob(rs.getString(4)) ;
obj.setYoe(rs.getString(5)) ;
obj.setMajsub(rs.getString(6));
list.add(obj);
Gson gson= new Gson();
String json=gson.toJson(obj);
System.out.println("In DAO");
System.out.println(json);
list1.add(json);
System.out.println("List1");
}
}
catch (SQLException | ClassNotFoundException e) {
System.out.println(e.getMessage());
}
return list1;
}
Forwarding data from servlet to jsp(Grid.jsp)
Grid.jsp
<div id="grid"></div>
<script>
$(document).ready(function() {
var dataSource= new kendo.data.DataSource({
transport:{
read:{/* I want to know how to read data here , how to code ?*/,
dataType : "json",
type: "POST",
}
},
schema:{
data: "xdata.rows",
model:{
id:"tid",
fields:{
// tid:{editable:false},
tid:{type:"String"},
name:{type:"String"},
gender:{type:"String"},
dob:{type:"String"},
yoe:{type:"String"},
majsub:{type:"String"}
}
}
},
pageSize:20,
batch:true
});
$("#grid").kendoGrid({
dataSource:dataSource,
height:350,
scrollable: true,
columns:[{field: "tid",title:"Teacher Id",width: "130px"},
{field: "name",title:"Name",width: "130px"},
{field: "gender",title:"Gender",width: "130px" },
{field: "dob",title:"Date of Birth",width: "130px"},
{field: "yoe",title:"Year of Experience",width: "130px"},
{field: "majsub",title:"Major sub",width: "130px" },
{command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "popup"
});
});
I am just trying to read data to grid, so i didn't provide Update,Destroy,Create.
I successfully retrieve data from Database and changed it to JSON.
["{\"tid\":\"001\",\"name\":\"Varalakshmi\",\"gender\":\"Female\",\"dob\":\"01/08/1989\",\"yoe\":\"2\",\"majsub\":\"Physics\"}","{\"tid\":\"002\",\"name\":\"Lakshman\",\"gender\":\"Male\",\"dob\":\"05/08/1979\",\"yoe\":\"8\",\"majsub\":\"Maths\"}"]
I got this in Grid.jsp, when i tried to view it using
${list}
Data you are passing is not in correct json format.
Compare the changedData and yourData in the method.
Data is required in array form for Grid, that's why I am converting it into array form. If you have data in array then pass that directly.
that should be like :
var data5 = [{ "Id": 121, "referenceId": 18222, "status": "test", "message": 'kk', "ss": "ss" }, { "Id": 121, "referenceId": 18222, "status": "test", "message": 'kk', "ss": "ss" }, { "Id": 121, "referenceId": 18222, "status": "test", "message": 'kk', "ss": "ss" }];
You will need kendo js and css file for kendo grid.
Use these :
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.226/styles/kendo.common-material.min.css">
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.226/styles/kendo.material.min.css">
<script src="//kendo.cdn.telerik.com/2016.1.226/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.1.226/js/kendo.all.min.js"></script>
<div id="grid" data-role="grid" class="k-grid k-widget k-editable" style="height: 550px;">
<script>
$(document).ready(function () {
var yourData = ["\"tid\":\"001\",\"name\":\"Varalakshmi\",\"gender\":\"Female\",\"dob\":\"01/08/1989\",\"yoe\":\"2\",\"majsub\":\"Physics\"}", "{\"tid\":\"002\",\"name\":\"Lakshman\",\"gender\":\"Male\",\"dob\":\"05/08/1979\",\"yoe\":\"8\",\"majsub\":\"Maths\"}"]
var changedData = "[{\"tid\":\"001\",\"name\":\"Varalakshmi\",\"gender\":\"Female\",\"dob\":\"01/08/1989\",\"yoe\":\"2\",\"majsub\":\"Maths\"}, {\"tid\":\"002\",\"name\":\"Lakshman\",\"gender\":\"Male\",\"dob\":\"05/08/1979\",\"yoe\":\"8\",\"majsub\":\"Maths\"}]";
var feedData = $.parseJSON(changedData);
$("#grid").kendoGrid({
dataSource: feedData,
navigatable: true,
pageable: true,
height: 550,
// toolbar: ["create", "save", "cancel"],
columns: [
{ field: "tid", title: "Unit Price" },
{ field: "name", title: "Units In Stock" },
{ field: "gender", title: "gender" },
{ field: "dob", title: "dob" },
{ field: "yoe", title: "yoe" },
{ field: "majsub", title: "majsub" },
],
editable: true
});
});
</script>
</div>

Proxy sends multiply requests from ExtJs store

My app send multiply request to server each time I insert new item to store. When the first item inserted it calls POST once, one more item ... twice and so on.
Im new at ExtJs, so can you help me in solving some qustions:
First of all what the sync method do, why (GET, POST, PUT, DELETE) methods are not called without store.sync() method invok?
Why my post method multiply requests?
Why store.remove() (DELETE) method throws 400 error (Bad request) when the PUT method works fine?
Thank you in advance
my edit controller:
Ext.define('MVC.controller.Edit', {
extend: 'Ext.app.Controller',
init: function () {
this.control({
'editForm > button#SaveRecord': {
click: this.onSaveButtonClick
},
'editForm > button#DeleteButton': {
click: this.onDeleteButtonClick
}
});
},
onSaveButtonClick: function (btn) {
//get reference to the form
var detailView = btn.up('editForm');
//get the form inputs
var data = detailView.getValues();
//see if the record exists
var store = Ext.getStore('TestStore');
console.log(data.id);
var record = store.getById(data.id);
if (!record) {
record = Ext.create('MVC.model.Note', {
title: data.title,
created: new Date(),
updated: new Date(),
text: data.text
});
store.insert(0, record);
store.sync();
Ext.MessageBox.alert('Created', record.id);
return;
}
record.set(data);
store.sync();
//manually update the record
detailView.updateRecord();
},
onDeleteButtonClick: function (btn) {
//get reference to the form
var detailView = btn.up('editForm');
//get the form inputs
var data = detailView.getValues();
var store = Ext.getStore('TestStore');
var record = store.getById(data.id);
store.remove(record);
store.sync();
}
});
Store :
Ext.define('MVC.store.TestStore', {
extend : 'Ext.data.Store',
requires : [
'MVC.model.Note'
],
storeId : 'TestStore',
model : 'MVC.model.Note',
autoLoad: false,
proxy: {
type : 'rest',
url: 'rest/notes',
actionMethods : {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy : 'DELETE'
},
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json'
}
}
});
And model:
Ext.define('MVC.model.Note', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: 'string'
},
{
name: 'title',
type: 'string'
},
{
name: 'created',
type: 'date'
},
{
name: 'updated',
type: 'date'
},
{
name: 'text',
type: 'string'
}
]
});
Try to use record's methods:
1)Add proxy to you'r model like this:
Ext.define('MVC.model.Note',{
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: 'string'
},
{
name: 'title',
type: 'string'
},
{
name: 'created',
type: 'date'
},
{
name: 'updated',
type: 'date'
},
{
name: 'text',
type: 'string'
}],
proxy:
{
type: 'rest',
url: 'rest/notes',
reader:
{
type: 'json'
}
}
});
2)Now you can use methods: record.save() - will send PUT if it was loaded to store from server and record have id, or POST if this record was created with record.create();
record.destroy() - will send DELETE to server with id of record;
You can use Ext.ModelManager.getModel('Model_name').load(id) to send GET request to server for single record.
3)Use store.load() to GET array of records from server

Change status using Ajax in Java

I need to change status of my event in data base.For this I create button with drop down menu with all status that can be. When I push this button and choose some variant it is changing but in my event fields owner, city, address became empty. What is wrong??
function html_element(aData, status) {
var parent_element = $("<a/>",
{
"href" : "#"
}).click(aData, function(e) {
aData.status = status;
e.preventDefault();
$.ajax({
url : 'event-update',
dataType : 'json',
beforeSend : function() {
},
contentType : "application/json",
"type" : "POST",
data : JSON.stringify(aData),
success : function(response) {
$('td:eq(6)',nRow).html(response.status);
}
});
});
return parent_element;
};
var button = $(
"<button/>",
{
text : "Action",
"type" : "button",
"data-toggle" : "dropdown",
"class" : "btn btn-default dropdown-toggle",
});
function form_element(aData) {
var approve = html_element(aData, "APPROVED");
var pending = html_element(aData, "PENDING");
var refuse = html_element(aData, "REFUSED");
approve.html("Approve");
pending.html("Pending");
refuse.html("Refuse");
var final_element = div.append(button);
final_element.append(ul.append(li
.append(approve)
.append(pending)
.append(refuse)));
return final_element;
}
row = $('td:eq(7)', nRow).html(form_element(aData));
function change_request_status(id, element) {
$.ajax({
url : 'response-event',
beforeSend : function() {
console.log('start');
element.style.display = "none";
loader.insertAfter(element);
},
data : {
"status" : status,
"address": address,
"owner" : owner,
cityId : city
},
success : function(response) {
console.log(data);
element.nextSibling.style.display = "none";
if (response == "Request send") {
successRequest.insertAfter(element);
} else {
failRequest.insertAfter(element);
}
},
});
}

How to display jqxGrid in spring

I have to implement the jqxGrid using spring.I don't know how to do it on spring.Below is my controller class
AccountController.java:
#Controller
#RequestMapping(value="/account")
public class AccountsController {
#Autowired
private AccountService accountService;
#RequestMapping(value = "/list", method = RequestMethod.GET, headers =
"Accept=application/json")
public #ResponseBody ModelAndView listOfAccounts() {
ModelAndView modelAndView = new ModelAndView();
List<Accounts> accounts = accountService.getAccounts();
modelAndView.addObject("accounts", accounts);
return modelAndView;
}
}
I think the json data retrieved from Accounts.java class is in the format :
[{"id":"1","PeriodName":2000-2001,"PeriodStartDate":"2000-01-01","PeriodEndDate":"2001-12-31"},{"id":"2","PeriodName":2001-2002,"PeriodStartDate":"2001-01-01","PeriodEndDate":"2002-12-31"}]
Below is jquery get request for the json response and code for getting the jqxGrid:
$.get('account/list',function(responseJson) {
var data = responseJson;
var source =
{
datatype: "json",
datafields: [
{ name: 'id' },
{ name: 'PeriodName' },
{ name: 'PeriodStartDate' },
{ name: 'PeriodEndDate' }
],
id: 'id',
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
//columnsresize: true,
width: 800,
source: dataAdapter,
pageable: true,
//pagerButtonsCount: 10,
autoheight: true,
// editable: false,
pagerrenderer: pagerrenderer,
columns: [
{ text: 'Period Name', datafield: 'PeriodName', width: 200 },
{ text: 'Start Date', datafield: 'PeriodStartDate', width: 200 },
{ text: 'End Date', datafield: 'PeriodEndDate', width: 200 }
]
});
});
But i didn't get the grid on here.I don't know where is the problem in the above code.I have imported all js files for jqxGrid.Please help me to solve this
*I looked on your problem here is the same code (little modified). comment that pagerenderer code .You have not defined the pagerenderer function anywhere. It will work. here is the working code http://jsfiddle.net/qwm3z/ .
responseJson = <c:out value="${accounts}" />;
var data = responseJson;
var source =
{
datatype: "json",
datafields: [
{ name: 'id' },
{ name: 'PeriodName' },
{ name: 'PeriodStartDate' },
{ name: 'PeriodEndDate' }
],
id: 'id',
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
//columnsresize: true,
width: 800,
source: dataAdapter,
pageable: true,
//pagerButtonsCount: 10,
autoheight: true,
// editable: false,
// pagerrenderer: pagerrenderer,
columns: [
{ text: 'Period Name', datafield: 'PeriodName', width: 200 },
{ text: 'Start Date', datafield: 'PeriodStartDate', width: 200 },
{ text: 'End Date', datafield: 'PeriodEndDate', width: 200 }
]
});
and why are you making grid in each response? you can make one time and update it for every get request.*

Categories