how can reload the jqgrid with in interval - java

Hi I have a grid which used to display call details. It is displaying all incoming calls so , I need the jqgrid reload after a particular interval. Means it need automatically reload after interval .
my code is in test.jsp:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "callDetails.html",
type: "post",
dataType: "json",
success: function (data) {
var results=data.rows;
$("#jQGrid").html("<table id=\"list1\"></table><div id=\"page1\"></div><div id=\"icon\" class=\"iconcls\"></div>");
jQuery("#list1").jqGrid({
url: "callDetails.html",
datatype: 'json',
mtype:'post',
width:930,
height: 200,
shrinkToFit:true,
colNames:['Call Id','Caller Name','CallerNo','Callee Name','Callee No','Date','Time','Status','Call Duration'],
success : function(data){
},
colModel:[
{name:'callId',index:results.callId,width:20,sortable:true} ,
{name:'callFromName',index:results.roleName,width:30,sortable:false},
{name:'callFromNo',index:results.callFromNo,width:20,sortable:false},
{name:'callToName',index:results.callToName,width:30,sortable:false},
{name:'callToNo',index:results.callToNo,width:20,sortable:false},
{name:'callDate',index:results.callDate,width:20,sortable:false},
{name:'callTime',index:results.callTime,width:20,sortable:false},
{name:'callState',index:results.callState,width:20,sortable:false},
{name:'callDuration',index:results.callDuration,width:20,sortable:false}
],
jsonReader: { repeatitems : false, id: "0" },
multiselect: false,
viewrecords: true,
headtitles: true,
paging: true,
loadtext : "Loading Call list...",
rowNum:10,
rowList:[10,20],
pager: jQuery("#page1"),
loadonce:false,
caption:"Incoming Call"
}).navGrid('#page1',{edit:false,add:false,del:false,search:false});
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
</script>
<div id="jQGrid" style=padding:10px;10px;10px;10px></div>

It is resolved by
<script type="text/javascript">
window.setTimeout( refreshGrid, 5000);
function refreshGrid()
{
var grid = jQuery("#list1");
grid.trigger("reloadGrid");
window.setTimeout(refreshGrid, 5000);
}
</script>

Related

Make a pie chart with tymeleaf highcharts spring mvc java

I want to create a pie chart with a dynamic data in highcharts
i really need your help
i wanna make a pie chart that counts the gender
here is my code
im really stuck there
..........................................................................
Controller :
#RequestMapping("/piechart")
public ResponseEntity<?> getAll(Model model) {
List<user> list = userRepository.allusers();
return new ResponseEntity<>(list,HttpStatus.OK);
}
Repository :
#Query(value=" SELECT *,count(*) AS count_gender FROM user GROUP BY gender", nativeQuery = true)
List<User> allusers();
HTML:
<body>
<div id="container" style="width: 550px; height: 400px; margin: 0 auto"></div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script th:inline="javascript">
$.ajax({
url: 'piechart',
dataType:'json',
success: function(result){
var series=[];
var data= [];
for(var i=0;i<result.length;i++){
var object={};
object.name=result[i].gender;
object.y=result[i];
data.push(object);
}
var seriesObject={
name:'percentage',
colorByPoint: true,
data: data
}
series.push(seriesObject);
drewPiechart(series);
}
})
function drewPiechart(series){
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
},
tooltip: {
formatter: function(){
return 'y value: '+this.y+'<br/>is '+this.percentage+'% of total ('+this.total+')';
}
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
},
showInLegend: true
}
},
series: series
});
}
</script>
</body>
</html>
here is my result:
it shows nothing bcz i didnt know how to get the count result of the query on the yaxis

Getting 400 bad request error in Jquery Ajax POST in jsp file

I am performing simple crud operation during this I am getting 400 bad request error on console
i.e. POST http://localhost:8080/student/getDetails 400
my code :
<body>
<form >
Enter Student id: <input type="number" id="id" name="id"/><br/>
<button id="selectButton" onclick="getStudent()">Get Student</button>
</form>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function getStudent() {
$.ajax({
type: "POST",
url : "/student/getDetails",
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data)
{
alert(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
</body>

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.

Code inserting into database twice

I have the form
<aui:form action="<%= editURL %>" method="POST" name="fm">
<aui:fieldset>
<aui:input name="name" />
<aui:input name="url" />
<aui:input name="address" />
</aui:fieldset>
<aui:button-row>
<aui:button type="submit" />
<aui:button name="cancel" value="Cancel"/>
</aui:button-row>
</aui:form>
and this piece of javascript code which is inserting into database twice I don't know why.
<aui:script use="aui-base,aui-form-validator,aui-io-request">
AUI().use('aui-base','aui-form-validator',function(A){
var rules = {
<portlet:namespace/>name: {
required: true
},
<portlet:namespace/>url: {
url: true
},
<portlet:namespace/>address: {
required: true
},
};
var fieldStrings = {
<portlet:namespace/>name: {
required: 'The Name field is required.'
},
<portlet:namespace/>address: {
required: 'The Address field is required.'
},
};
alert("validator");
new A.FormValidator({
boundingBox: '#<portlet:namespace/>fm',
fieldStrings: fieldStrings,
rules: rules,
showAllMessages:true,
on: {
validateField: function(event) {
},
validField: function(event) {
},
errorField: function(event) {
},
submitError: function(event) {
alert("submitError");
event.preventDefault(); //prevent form submit
},
submit: function(event) {
alert("Submit");
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
alert("inside success");// not getting this alert.
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
}
}
});
});
</aui:script>
However if I add the following piece of code, which is redundant because it is already present inside the submit block of above code and is not triggered any way because I do not have any save button in the form, then the value is inserted only once.
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
This code generates Uncaught TypeError: Cannot read property 'on' of null which I think is because there is no save button in the form. But adding this code, the value is inserted into database just once which is what I want but the logic is flawed. How can I get the results I want by just by using the first piece of code?
The insertion was happening twice. Once from the default form submit and other from the A.io.request. Adding this piece of code
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
resulted in the insertion only once. This code has obviously no relevance because there is no save button in the form. Hence there was Uncaught TypeError: Cannot read property 'on' of null which masked the flaw and prevented the form from being submitted twice.
Removing the above piece of code and preventing the default submit (by adding onSubmit="event.preventDefault(); in the form tag) resolves the issue.

check success and error in ajax

I have a button in jsp like this.
<input class="submit_button" type="submit" id="btnPay" name="btnPay" value="Payment"
style="position: absolute; left: 350px; top: 130px;" onclick="javascript:payment();">
The javascript function calls the java servlet and the servlet calls the function "callprocedure()" when the button is clicked.
<script>
function payment()
{
var req = $.ajax({
type: "POST",
url: '/context/Servlet',
success: function(result){
//when successfully return from your java
alert('Payment done successfully...');
}
}, error: function(){
// when got error
alert("sorry payment failed");
}
});
}
</script>
Now all works fine but my problem is to check the success or error in ajax. How can i check the success or error in ajax in my case.
Thanx in advance ...
You are doing that correctly, However you have syntax error in your code :
function payment() {
var req = $.ajax({
type: "POST",
url: '/context/Servlet',
success: function (result) {
// alert data returned by jsp
alert(result);
alert('Payment done successfully...');
},
error: function (jqXHR,textStatus,errorThrown) {
// when got error
alert("sorry payment failed :" + errorThrown);
}
});
}
you can use parameter passed to error callback to know the cause of error
More info
http://api.jquery.com/jQuery.ajax/
Another way to do it (not very efficient though):
Check the returned value from servlet.
$.post('Servlet',paramName:paramValue,...},function(result) {
if (result.substring(0,...)=='(expected result)'){ //success
}else{ //error
}
});
Hope it helps

Categories