Integrate Flotr2 charts Dynamically from DB - java

I am new to this flotr and beginner of java. How can i create a flotr chart that retervie data from data base. i can create chart by static values but using database how can i create flotr charts. please give me some Example with database . so that i can work for all the othe charts.please help guide me the process to retervie data ffrom database into flotr charts using java or jsp.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> Line Chart</title>
<style>
body {
margin: 20px;
padding:10px;
}
#example {
width: 500px;
height: 300px;
}
</style>
</head>
<body>
<div id="example"></div>
<script type="text/javascript" src="./js/flotr2.min.js"></script>
<script type="text/javascript">
(function basic(container) {
var
d1 = [[0, 3], [4, 8], [8, 5], [9, 13]], // First data series
graph;
// Draw Graph
graph = Flotr.draw(container, [ d1],{
lines: {show: true, fill: true,color: 'yellow'},
points: {show: true,radius: 3,fillColor:'yellow'},
title: "Line Chart",
subtitle: "Employee"}
);
})(document.getElementById("example"));
</script>
</body>
</html>

Well I'm not sure what you mean by Java...do you mean Javascript? Because Flotr2 works on web-based platforms. But to integrate a database into making a chart with Flotr2 is actually really easy.
I use php, but you could use asp or jsp as well for this. Basically what you need to do is write some php code that will access the database and then just echo out the javascript code with the php variables. Like so:
<script type="text/javascript">
(function (){
<?php
$mysqli = new mysqli("host", "user", "password", "database");
if(!($stmt = $mysqli->prepare("SELECT attribute FROM table WHERE condition"))){
echo "Prepare Failed: (" . $mysqliprivate->errno . ") " . $mysqliprivate->error;
}
else{
$stmt->bind_param("s", $condition);
$stmt->execute();
$stmt->bind_result("$result");
echo "var dataset = [";
$i = 0;
while($stmt11->fetch()){
echo " [" . $i . ", " . $result. "]";
echo ",";
$i++;
}
echo "];";
$stmt->close();
?>
And then in your javascript code
graph = Flotr.draw(container, [ d1],{
instead of d1, replace that with dataset the variable you declared back at your php code

Related

How to pass a variable from HTML to Java?

I want to pass a variable from HTML to Java. For this, I wrote the following code:
<!doctype html>
<html>
<title>How to create a typewriter or typing effect with jQuery</title>
<div id="example1">fsdfsdfojsdlk sdfj lskdhfk sdf </div>
<style>
body{
background: transparent;
color: #ec5a62;
}
#container{
font-size: 7em;
}
</style>
</head>
<body>
<div id="container"></div>
<!--
We use Google's CDN to serve the jQuery js libs.
To speed up the page load we put these scripts at the bottom of the page
-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script>
//define text
var text = ("document.getElementById("example1")");
//text is split up to letters
$.each(text.split(''), function(i, letter){
//we add 100*i ms delay to each letter
setTimeout(function(){
//we add the letter to the container
$('#container').html($('#container').html() + letter);
}, 30*i);
});
</script>
</body>
</html>
But it is not working. How can I achieve this?
Please do help me.
I'm using var text =("document.getElementById("example1")");
But its not working.
to get value use var x=document.getElementById("example1").value;
your code should be like this:
var text=document.getElementById("example1").value;
//text is split up to letters
$.each(text.split(''), function(i, letter){
//we add 100*i ms delay to each letter
setTimeout(function(){
//we add the letter to the container
$('#container').html($('#container').html() + letter);
}, 30*i);
});

Pagination: how to load first page with AJAX

I'm writing online shopping application using Struts 2.
In front-end I'm using jsp, twitter bootstrap, jquery, moustache.js template, twbs pagination plugin and some javascript.
I have Product entity and I want to display the list of products to the user in jsp page.
The way I'm doing it is async loading page with fix number(20) of products in json format and then obtaining them using mustache template.
All my code works except the time when user the first time sees this jsp page - first 20 products are not displaying. So when I'm moving from page to page it loads info, but as twbs plugin works through firing events it means that event is not triggered after jsp page loaded the first time.
So my question is whats the truly good way to fix this ?
Should I fire an event once or use $(document).ready() or $(document).onload() ?
I'm not an expert in javascript, so please be patient
<html>
<%# include file="/WEB-INF/jspf/head.jspf"%>
<body>
<%# include file="/WEB-INF/jspf/menu.jspf"%>
<div class="container">
<ul class="sync-pagination pagination"></ul>
<div id="products" style="width: 50%"></div>
<ul class="sync-pagination pagination"></ul>
</div>
<script type="text/javascript"
src="webjars/mustachejs/0.8.2/mustache.js"></script>
<script id="products-template" type="text/mustache-template">
<ul class="list-group">
{{#.}}
<li class="list-group-item">
<label for="{{name}}">Name: /label> {{name}}
</br>
<label for="{{price}}">Price: </label> {{price}}
</br>
Full description...
</li>
{{/.}}
</ul>
</script>
<script type="text/javascript"
src="script/jquery.twbsPagination.min.js"></script>
<script type="text/javascript">
var records = "${requestScope.records}";
var recordsPerPage = 20;
var pages = Math.ceil(records / recordsPerPage);
$('.sync-pagination').twbsPagination({
totalPages : pages,
visiblePages : 7,
onPageClick : function(event, page) {
$('#products').html(changePage(page));
}
});
function changePage(page) {
pnumber = page || 1;
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products?page=' + pnumber,
success : function(products) {
var template = $('#products-template').html();
var info = Mustache.render(template, products);
$('#products').html(info);
}
})
}
</script>
</body>
</html>
You need to call changePage(); on the initial load. You might also want to call this when the page finishes loading everything by using $(document).ready();
<script type="text/javascript">
var records = "${requestScope.records}";
var recordsPerPage = 20;
var pages = Math.ceil(records / recordsPerPage);
$('.sync-pagination').twbsPagination({
totalPages : pages,
visiblePages : 7,
onPageClick : function(event, page) {
$('#products').html(changePage(page));
}
});
function changePage(page) {
pnumber = page || 1;
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products?page=' + pnumber,
success : function(products) {
var template = $('#products-template').html();
var info = Mustache.render(template, products);
$('#products').html(info);
}
})
}
//Add this in here
changePage();
</script>

Google charts with jstl forEach

Hi I am trying to render google chart on my java program. but it doesn't display at all. Google chart api is implemented in .jsp file. Since my java code delivers correct data (I checked with system print), there must be something wrong on my jsp file. specially [A] part..
I am very new to this world.
Can anyone point out what did I do wrong in .jsp file.
my jsp file
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('number', 'Data value');
data.addRows([
<c:forEach var="dataIntValue" items="${dataInt}">
['${dataIntValue}'], //---- [A]
</c:forEach>
]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height: 340, min: 0});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 540px;"></div>
</body>
</html>
Update
when I look at the page source on browser.. it shows like this..
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('number', 'Data Value');
data.addRows([
['100'],
['200'],
['300'],
['400'],
['500'],
['110'],
['120'],
['130'],
['140'],
['200'],
]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 1000, height: 540, min: 0});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 540px;"></div>
</body>
</html>
and the values are right ones.. but I don't know it should be with this '' together.. Can that be problem? e.g. it shows this ['400'], but may be should like this [400] without ''? but I don't know why it is with ''? what did I do in my code... and why with '400'? not just the value 400...
update 2
applied the comment advice and then, get a syntax error , can't compile at all..
what I did based on advice: remove the ' ' in the [A]
so jsp file looks like this.. all same only [A] part is different by removing the ' '.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('number', 'Data Value');
data.addRows([
<c:forEach var="dataIntValue" items="${dataInt}">
[${dataIntValue}], //---[A]
</c:forEach> //----[B]
]); //----[B]
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 1000, height: 540, min: 0});
} //----- [c]
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 540px;"></div>
</body>
</html>
These are the syntax errors.. what I get after removing ' ' from [A]
Multiple annotations found at this line:
- Syntax error on tokens, ArrayLiteralHeader expected
instead
- Syntax error, insert "]" to complete
MemberExpression
- Syntax error, insert ")" to complete Arguments
- Syntax error on tokens, delete these tokens
- Syntax error, insert "]" to complete ArrayLiteral
result here: can compile but no charts appears on browser: Comments from (JB Nizet)=> What you posted is not an error you get at runtime. It's an error that your IDE, which tries to interpret your code as pure JavaScript, generates. The code is correct. Deploy it, run it, ans see if it works
update 3 & solved: comma should be there in [A] and google chart code was problem should be like this:
working code:
1) changed to google.visualization.arrayToDataTable instead google.visualization.DataTable.
2) I was missing first column element in here (so should have 2 elements like this) ['${dataIntValue}', ${dataIntValue}], instead with only one element this was wrong: [${dataIntValue}],
Correct code=>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
//---[solution] modified from here
var data = google.visualization.arrayToDataTable([
['number', 'Data Value'],
<c:forEach var="dataIntValue" items="${dataInt}">
['${dataIntValue}', ${dataIntValue}],
</c:forEach>
]); //--- until here.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height: 340, min: 0});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 600px; height: 340px;"></div>
</body>
</html>

d3.js code in not working on JPS

I am new in d3.js and i am trying to make a d3.js program in JSP. I have a two files
1) HTML
2) javascript
now when i linked javascript in HTML file then it shows pie chart.
Problem: when i am trying to run this code in jsp and its not working? I dont understand that just by changing the extension from html to jsp, why the program was stop showing pie chart?
your suggestions would be helpful...
this is the code-
This is the JSP file
<html>
<head>
<link rel="stylesheet" type="text/css" href="background.css" />
<script type="text/javascript" src="libss/d3.js" charset="UTF-8"></script>
<script type="text/javascript" src="libss/d3.min.js" charset="UTF-8"></script>
<script src="http://d3js.org/d3.v3.js" charset="UTF-8"></script>
</style>
</head>
<body>
<script type="text/javascript" src=" E:\javaa\data_vis\data-vis-new\libss\temp.js">
</script>
<script>
dataset = [ 7, 66, 20, 45, 6, 25 ];
</script>
</body>
</html>
and this is temp.js file-
//Width and height
var w = 300;
var h = 300;
var outerRadius = w / 2;
var innerRadius = 0;
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var pie = d3.layout.pie();
//Easy colors accessible via a 10-step ordinal scale
var color = d3.scale.category10();
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Set up groups
var arcs = svg.selectAll("g.arc")
.data(pie(dataset))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");
//Draw arc paths
arcs.append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
//Labels
arcs.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
This is because you didn't put the script tag in the right place.
Solution #1
Simply try move your scripts lib into bottom of body:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
...
// try import it here
<script type="text/javascript" src="lib/pie.js"></script>
</body>
</html>
plnkr
Solution #2
If you insists putting the lib into head, try adding a defer attribute in script element:
<head>
<meta charset="utf-8">
<title>D3: Pie layout</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js" defer></script>
<script type="text/javascript" src="lib/pie.js" defer></script>
<script>
dataset = [1,2,3,4,5];
</script>
</head>
For reasons why your code can not work, see this thread:
Where is the best place to put tags in HTML markup
I get the answer. I did not get the logic my program start working without any problem.
Here is the solution-
just placed your own .js file below the dataset variable like this...
<body>
<script>
dataset = [ 7, 66, 20, 45, 6, 25 ];
</script>
<script type="text/javascript" src=" E:\javaa\data_vis\data-vis-new\libss\temp.js">
</script>
</body>
if u dont get it just comment above with # and my name and will tell you later...

how to display a stack of image followed by name in order

i wan to ask that if my machine got 1000/10000 of image and each image is named follow by order (1.jpg, 2.jpg, 3.jpg, 4.jpg .... 10000.jpg) , how to do it to let it display follow th order ?
i saw a lot of question on internet that they put it on the JLabel but many of them say it won't work . i have even try a few method to let it display like javascript but it is not the result i want.
I wish the program is running like 0.5 seconds a time and display the image followed the image number.
Can anyone guild me through this ? thanks in advance
==================================================================================
update : this is my javascript code
<html>
<head>
</head>
<body>
<img src="images/image1.jpg" alt="rotating image" width="600" height="500" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'); // change to match image ID
//var imageDir = 'images/'; // change to match images folder
var delayInSeconds = 1; // set number of seconds delay
// list image names
var images = ['1.jpg','2.jpg', '3.jpg', '4.jpg'];
// don't change below this line
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 50);
})();
</script>
</body>
</html>
first of all, you need to preload images, to do it, you can add them in hidden div. Then replace your original image with it.Something like this:
<html>
<head>
<title>ViewImage</title>
<script type="text/javascript" src="/jquery-1.4.2.min.js"></script>
<script>
var img_num = 1;
$(function(){
window.setInterval(function(){
var img = $('#hiden-img');
if(img[0].complete==true)
$('#real-image').attr('src', img.attr('src'));
img_num++;
if(img_num>10000)img_num=1;
img.attr('src', '/img/'+img_num+'.jpg');
}, 500);
});
</script>
</head>
<body>
<img id="hiden-img" style="display:none;"/>
<img id="real-image" src="/img/1.jpg"/>
</body>
</html>
try it like this. Download jquery and place it in your site, replace paths "/path/to/img" (2 times) and "/path/to/jquery" to your real paths. this should do the trick.
you do not need to refresh page every second. You do not need to refresh it all.
It's works on my site.

Categories