Make a pie chart with tymeleaf highcharts spring mvc java - 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

Related

on selecting a row on left jqgrid, the associated rows should be highlighted in right side jqgrid

I have a requirement, where i will be having two jqgrids in a single page. #grid1 is list of roles and #grid2 is list of operations that a particular role can perform. Now when i select a row(role) in grid1, the operations associated to these particular role should be highlighted in some color in grid2.
I am including my code here
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Role Management</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.js'> </script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="http://trirand.com/blog/jqgrid/themes/ui.jqgrid.css">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script type='text/javascript' src="http://trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js"></script>
<script type='text/javascript' src="http://trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js"></script>
<style type='text/css'>
.ui-jqgrid-btable .ui-state-highlight { background: yellow; }
.ui-jqgrid-htable .ui-jqgrid-labels {background-color:green}
..ui-pg-table {background:green}
.ui-jqgrid .ui-widget-header {
border: 1px solid #0b3e6f;
background: #7da600;
color: #40453a;
}
.ui-jqgrid .ui-jqgrid-bdiv { overflow-y: scroll }
</style>
<script type='text/javascript'>
jQuery(document).ready(function () {
var lastSel,lastSel1,
grid=$("#roleMgmtTable"),
gridavail=$("#AvailableOperations");
grid.jqGrid({
url: "rolesList",
datatype: "json", 
jsonReader: {repeatitems: false, id: "ref"},
colNames:['Id','role Name','Description', 'Status'],
colModel:[
{name:'roleId',index:'roleId',width:150,editable:true,sorttype:'text',hidden:true},{name:'roleName',index:'roleName',width:150,editable:true,sorttype:'text',editrules:{text:true},},{name:'description',index:'description', width:150,editable:true,sorttype:'text'},{name:'status',index:'status', width:150,editable:true,sorttype:'text'}],
rowList:[10, 20, 50, 100],
pager: "#pagingDiv",
viewrecords: true,
sortname: 'roleName',
sortorder: "asc",
editurl: "LoadJsonDataServlet?type=BS21 7RH",
caption: "Role Management",
height:200,
editurl: 'rolesList',
ondblClickRow: function(id, ri, ci) {
grid.jqGrid('editRow',id,true,null,null, 'rolesList');
},
  });
grid.jqGrid('navGrid',"#pagingDiv",{edit:true,add:true,del:true,search:false, refresh:false},
// Edit options
{
savekey: [true, 13],
reloadAfterSubmit: true,
//jqModal: true,
closeOnEscape: true,
closeAfterEdit: true,
height:300,
width:500,
bSubmit: "Update",
bCancel: "Close",
bClose: "Close",
editCaption: "Edit Record"
},
// Add options
{
savekey: [true, 13],
reloadAfterSubmit: true,
//jqModal: true,
height:300,
width:500,
bSubmit: "Save",
bCancel: "Close",
bClose: "Close",
addCaption: "Add Record",
closeOnEscape: true,
closeAfterAdd: true,
closeOnEscape: true
},
// Delete options
{
closeOnEscape: true,
multipleSearch: false,
reloadAfterSubmit:true,
closeAfterSearch: false,
bSubmit: "Delete",
bCancel: "Close",
bClose: "Close",
onclickSubmit: function (params) {
var list = $("#roleMgmtTable");
var selectedRow = list.getGridParam("selrow");
rowData = list.getRowData(selectedRow);
return rowData;
}
}
);
gridavail.jqGrid({
url: "optsList",
datatype: "json",
jsonReader: {repeatitems: false, id: "ref"},
colNames:['Id','Name','Description'],
colModel: [{name:'id',index:'id',width:150,editable:true,sorttype:'text',hidden:true},{name:'name',index:'name', width:150,editable:true,sorttype:'text',editrules:{text:true},},{name:'description',index:'description',width:300,editable:true,sorttype:'text'}],
rowList:[10,20,60,100],
pager: "#pagingDiv1",
viewrecords: true,
sortname: 'name',
sortorder: "asc",
editurl: "LoadJsonDataServlet?type=BS21 7RH",
caption: "Available Operations",
height:200,
multiselect: true,
editurl: 'clientArray',
ondblClickRow: function(id, ri, ci) {
// edit the row and save it on press "enter" key
gridavail.jqGrid('editRow',id,true,null,null, 'clientArray');
},
onSelectRow: function(id) {
if (id && id !== lastSel1) {
if (typeof lastSel1 !== "undefined") {
gridavail.jqGrid('restoreRow',lastSel1);
}
lastSel1 = id;
}
}
});
$('#save_role_operation').click(function(){
var myGrid = $("#roleMgmtTable");
selRowId = myGrid.jqGrid ('getGridParam', 'selrow');
roleIdValue = myGrid.jqGrid ('getCell', selRowId, 'roleId');
var avaGrid = $("#AvailableOperations");
selopIds = avaGrid.jqGrid('getGridParam','selarrrow');
selOpArrVal=""
if(selopIds==""){
}else if(selopIds!=""){
selOpArr = selopIds.toString().split(",");
for(i=0;i<selOpArr.length;i++){
if(i < selOpArr.length-1){
selOpArrVal = selOpArrVal + avaGrid.jqGrid ('getCell', selOpArr[i], 'id') +",";
}else if(i==selOpArr.length-1){
selOpArrVal = selOpArrVal + avaGrid.jqGrid ('getCell', selOpArr[i], 'id');
}
}
console.log("roleId value="+roleIdValue);
console.log("selOpArrVal value="+selOpArrVal);
$.ajax({
data: {"roleId":roleIdValue,"avaOpList":selOpArrVal},
success: function(data){
console.log("device control succeeded"+data);
},
error: function(errMsg){
console.log("Device control failed");
},
type: 'POST',
url: "roleOperationsList"
});
}
});
});
</script>
</head>
<body>
<form id='myForm'>
<div style="float:left;width:1155px;height:100%">
<table border=0>
<tr>
<td style="border-left: 3px solid #cdd0d4;"/>
<td>
<table style="width:100%;">
<tr><td bgcolor="#666666" style="color:white">Application Roles</td> </tr>
<tr>
<td>
<div>
<div style="width:100%;border:1px;">
<div style="float: left;border:1px;">
<table id="roleMgmtTable"></table>
<div id="pagingDiv"></div>
</div>
<div style="float: left;padding:0px 0px 0px 20px">
<table id="AvailableOperations"></table>
<div id="pagingDiv1"></div>
<div style="float:left;">
<div style="padding:10px 0px 0p 0px">
<div style="float: left;background: #7da600;">
<button class="save_role_operation" id="save_role_operation">Save Role Operation</button></div>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
</table>
</td>
<td style="border-left: 3px solid #cdd0d4;"/>
</tr>
</table>
<div >
<div style="display:inline-block;" >Home</div>
</div>
</div>
</form>
 </body>
</html>
when i select role on left grid and operations on right grid and click on the button save role operations, the roleId and operationId will be saved into an association table with columns role_id and operation_id. SO now if i select the role(row), i should see the associated operations for this in the right grid.
can anyone help me through this?
You can add onSelectRow callback on left grid (master grid). The callback will be called by jqGrid after a row in the left grid (master grid) will be selected. You will get the id of the selected row (the rowid).
The next step: you should get somewhere the information which operations are associated with the role. For example you can hold the information in the hidden column of roles grid. You need to include the information in the server response which you use for filling the grid. The operationIds column of Roles grid can contains for example comma separated list of the ids of operations. In the case the implementation could be the following:
onSelectRow: function (rowid) {
var operationIds = $(this).jqGrid("getCell", rowid, "operationIds").split(","),
i, n = operationIds.length;
gridavail.jqGrid("resetSelection");
for (i = 0; i < n; i++) {
gridavail.jqGrid("setSelection", operationIds[i]);
}
}

How to print google-annotated-chart by clicking on print button, just like normal print as save it as a pdf programatically?

How to print Google annotated chart by clicking on print button in a web page?
In my code, I used window.print() method, but when I print the page, chart disappears from the webpage and rest of the content is printing.
Please help me.
<!DOCTYPE html> <html> <head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"><!--
css for datepicker -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><!--
Javascript for datepicker -->
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]}); $(document).ready(function(){
showGoogleChart('2013-12-01','2013-12-31');
//============================= Onpage load calling chart function
$( "#from" ).datepicker({ changeMonth: true,
dateFormat:'yy-mm-dd', numberOfMonths: 3, onClose: function(
selectedDate ) { $( "#to" ).datepicker( "option", "minDate",
selectedDate ); } }); $( "#to" ).datepicker({
dateFormat:'yy-mm-dd', changeMonth: true, numberOfMonths: 3,
onClose: function( selectedDate ) { $( "#from" ).datepicker(
"option", "maxDate", selectedDate ); } }); });
//==================== OnChange date call google chart
================== function getChartdate(){ alert("hi"); var startdate = $('#from').val(); var enddate = $('#to').val();
showGoogleChart(startdate,enddate); //===========On button click
calling chart function========= }
function showGoogleChart(startdate,enddate){
var queryObject="";
var queryObjectLen="";
var postdata = {"startDate":startdate,"endDate":enddate};
$.ajax({
type : 'POST',
url : 'testPages.jsp',
data:postdata,
dataType:'json',
success : function(data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
google.setOnLoadCallback(drawChart(queryObject,queryObjectLen));
},
error : function(xhr, type) {
alert('server error occoured')
}
});
}
function drawChart(queryObject,queryObjectLen) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'date');
data.addColumn('number', 'temp');
for(var i=0;i<queryObjectLen;i++)
{
var name = queryObject.empdetails[i].date;
var empid = queryObject.empdetails[i].temp;
data.addRows([
[name,parseInt(empid)]
]);
}
var options = {
title: 'Employee Information',
}; var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options); }
</script>
</head>
<body>
<div style="margin: 50px;">
<label for="from">From</label> <input type="text" id="from" name="from"> <label for="to">to</label> <input type="text"
id="to" name="to"> <input type="button" id="changeChart"
onclick="getChartdate();" value="Change Chart"/>
</div>
<div id="chart_div"></div>
</body>
</html>
The method window print() will simply open the print dialog. How the page is formatted for print depends on how the browser formats webpages and the print stylesheet if present.
Assuming the chart is some kind of image (or canvas), it might be that the browser choses to strip images when printing. Especially if the image is added using css background-image: url(...) because it assumes a background image (like background-color) is just for decoration and would waste ink if printed.
A plain img tag should print though in most cases unless some css is removing it for print...

How to add selenium test coverage for jquery autocompleter text field

I have a text field , and jquery auto completer is binded to it.
html
<div id="autoCompleter">
<input type="text" name="symbol" />
</div>
javascript
$('#autoCompleter').delegate("input", "focus", AutoCompleter);
var AutoCompleter = function(event) {
$(this).autocomplete({
source: function(request, response) {
jQuery.extAjax({
url: url,
data: data,
success: response
});
},
select: function(event, ui) {
if (ui.item.value.match(/^Enter more characters...$/)) {
return false;
}
},
focus: function(event, ui) {
if (ui.item.value.match(/^Enter more characters...$/)) {
return false;
}
},
minLength: 2
});
$(this).autocomplete("search", $(this).val());
};
I have tried in the following way
#Test
public void autoCompleter() {
driver.findElementByName("symbol").sendKeys("22");
common.patientlyFindElement(By.xpath("//ul[contains(#class, 'ui-autocomplete')]//a[contains(.,'Enter more characters...')]")).click();
assertEquals(driver.findElementByName("symbol").getAttribute("value"), "22");
}

JSON value doesn't well formed in jquery autocomplete

I have problem with my jquery autocomplete script.
Here is my code:
back
<?php
require_once("include/global.php");
require_once("include/con_open.php");
$q = "select name, id from tbl_hotel";
$query = mysql_query($q);
if (mysql_num_rows($query) > 0) {
$return = array();
while ($row = mysql_fetch_array($query)) {
array_push($return,array('label'=>$row["name"],'id'=>$row["id"]));
}
}
echo(json_encode($return));
front
<input type="text" id="hotel" />
<link rel="stylesheet" type="text/css" href="http://cdn0.favehotels.com/v2/style/autocomplete/jquery.ui.all.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "#hotel" ).autocomplete({
position: { my : "right bottom", at: "right top" },
source: "hotel-search.php",
minLength: 2,
select: function( event, ui ) {
window.location.href=ui.item.id;
}
})._renderItem = function( ul, item ) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").text(item.label))
.appendTo(ul);
};
});
</script>
source: "hotel-search.php" returning [{"label":"A", "id":"1"}]
when I changet the line source: "hotel-search.php" to source: [{"label":"A", "id":"1"}]
it doesn't work yet.
but when i change it to source: [{label:"A", id:"1"}] it works fine.
what should I do to make return of "hotel-search.php" to be like {label:"Hotel A", id:"1"} not {"label":"Hotel A", "id":"1"}
Naufal Abu Sudais: "it doesn't work yet" refers the autocomplete keep showing up all list. It keep showing "A", even I typed "B"
When you use autocomplete with AJAX call, a GET parameter is sent to the service, term :
hotel-search.php?term=WhatYouTypeInAutocomplete
So if you want shortest list, You must use $_GET['term'] in your PHP file to filter response items.
Try $.getJSON to let jQuery to get and parse JSON response as JSON Object :
$.getJSON('hotel-search.php', function(jsonData) {
$("#hotel" ).autocomplete({
position: { my : "right bottom", at: "right top" },
source: jsonData,
minLength: 2,
select: function( event, ui ) {
window.location.href=ui.item.id;
}
})._renderItem = function( ul, item ) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").text(item.label))
.appendTo(ul);
};
});

how can reload the jqgrid with in interval

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>

Categories