d3.js code in not working on JPS - java

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...

Related

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>

jsp: how to get value from session?

I get an String array from session and I want to show the String from the array.
I know javascript can't get data from session directly. Is there any method I can get the data from session and transfer it to javascrip?
My code as follows:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%String[] sele = (String[])session.getAttribute("selections");%>;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Expires" content="0">
<meta http-equiv="kiben" content="no-cache">
<title>Check List</title>
<script language="javascript" type="text/JavaScript" src="cookie.js">
</script>
<script text="text/javascript">
{
var selections = //String array form session
for(var v=0;v<selections.length;v++){
fillForm(selections[v]);
}
}
function fillForm(name){
var checkbox= document.createElement("input");
checkbox.type="checkbox";
checkbox.name=name;
checkbox.value=name;
checkbox.id=name;
var label = document.createElement("label");
label.htmlFor="id";
label.appendChild(document.createTextNode(name));
var container = document.getElementById("checklist");
container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(document.createElement("br"));
}
function submitAction(){
addUserName(document.getElementById("checklist"));
var elem = document.getElementById("checklist").elements;
for(i =0;i<elem.length;i++){
elem[i].checked = true;
}
var form = document.getElementById("checklist");
form.submit();
}
</script>
</head>
<body>
<form id="checklist" action="selection">
</form>
<Button type="button" onclick="submitAction()" name="submit">Submit</button>
</body>
</html>
Simply use JSP Expression Language and JSP JSTL
<script>
alert("value: ${selections}");
</script>
Here selections is an attribute that is set in any scope page, request, session or application.
You can directly access an attribute form session scope:
{sessionScope.selections}
Note: I don't know that Java ArrayList does work in JavaScript as well. If it doesn't work then simply set a comma separated string as session attribute and split it in JavaScript as shown below.
Sample code:
<script>
var selections = "${sessionScope.csv}".split(",");
for ( var v = 0; v < selections.length; v++) {
alert(selections[v]);
}
</script>
Here csv is a comma separated string value that is set in session scope.
Use JSP JSTL and EL instead of Scriplet that is more easy to use and less error prone.
You can achieve it in JSTL without using JavaScript. Simply iterate the list using <c:forEach> tag and add that much of check boxes and labels.
Sample code:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
...
<body>
...
<c:forEach items="${selections }" var="name">
<input type="checkbox" name="${name}" value="${name}" id="${name}">
...
</c:forEach>
</body>

Accessing java variable from javascript on same jsp

Is it possible to access a String type variable defined in jsp from a javascript on the same page?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
<script type="text/javascript">
foo();
function foo()
{
var value = "<%=myVar%>";
alert(value);
}
</script>
</head>
<body>
<%
String myVar="blabla";
%>
</body>
</html>
In eclipse I am getting an error
myVar cannot be resolved to a variable
This won't work since you're trying to use an undefined variable. The code is generated like this:
... = myVar;
//...
String myVar = "blabla";
Doesn't make sense, right? So, in order to make this work you should declare the variable before using it (as always):
<%
String myVar="blabla";
%>
<script type="text/javascript">
foo();
function foo() {
var value = "<%=myVar%>";
alert(value);
}
</script>
Still, usage of scriptlets is extremely discouraged. Assuming you're using JSTL and Expression Language (EL), this can be rewritten to:
<c:set name="myVar" value="blabla" />
<script type="text/javascript">
foo();
function foo() {
var value = "${myVar}";
alert(value);
}
</script>
If your variable has characters like " inside, then this approach will faile. You can escape the result by using <c:out> from JSTL:
var value = "<c:out value='${myVar}' />";
More info:
How to avoid Java code in JSP files?

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.

How do I make a image viewer like facebook?

I want to make an image viewer (for my website) like the one in Facebook (the old one). When the user click the next or back arrow it will change the picture and the URL of the page.
This is an example of what I want (http://www.facebook.com/pages/Forest-Ville/307556775942281)
Most importantly I want the page to reload with each click with new (URL, comment box, ads, etc.) I do not want to use any Cookies.
Now I am using this, but its completely different from what I want.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script language="JavaScript">
var NumberOfImages = 10
var img = new Array(NumberOfImages)
img[0] = "http://damnthisfunny.site40.net/1.jpg"
img[1] = "http://damnthisfunny.site40.net/2.jpg"
img[2] = "http://damnthisfunny.site40.net/3.jpg"
img[3] = "http://damnthisfunny.site40.net/4.jpg"
img[4] = "http://damnthisfunny.site40.net/5.jpg"
img[5] = "http://damnthisfunny.site40.net/6.jpg"
img[6] = "http://damnthisfunny.site40.net/7.jpg"
img[7] = "http://damnthisfunny.site40.net/8.jpg"
img[8] = "http://damnthisfunny.site40.net/9.jpg"
img[9] = "http://damnthisfunny.site40.net/10.jpg"
var imgNumber = 0
function NextImage()
{
imgNumber++
if (imgNumber == NumberOfImages)
imgNumber = 0
document.images["VCRImage"].src = img[imgNumber]
}
function PreviousImage()
{
imgNumber--
if (imgNumber < 0)
imgNumber = NumberOfImages - 1
document.images["VCRImage"].src = img[imgNumber]
}
</script>
<body>
<center>
<img name="VCRImage" src="http://damnthisfunny.site40.net/1.jpg" /></dr>
<br />
<a href="javascript:PreviousImage()">
<img border="0" src="left1.jpg" /></a>
<a href="javascript:NextImage()">
<img border="0" src="right1.jpg" /></a>
</center>
</body>
</html>
Any ideas ?

Categories