Pie chart using google chart - java

I am trying to run this javascript code which retrive data from the database and a string is created this string is passed to the draw method which creates a pie chart but it is not displaying any thing please help....
<%#page import="java.io.File"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="Persistence.FolderBroker"%>
<%#page import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<%
FolderBroker fb = new FolderBroker();
Connection conn = fb.insert();
ResultSet rs, rs1;
String s = "";
Statement st = conn.createStatement();
PreparedStatement query = conn
.prepareStatement("select sum(frequency) from tokendetails;");
rs = query.executeQuery();
rs.next();
int count = rs.getInt(1);
String sql = "select filename, sum(frequency) as freq from tokendetails group by filename;";
rs1 = st.executeQuery(sql);
while (rs1.next()) {
String file = rs1.getString(1);
File f = new File(file);
String files = f.getName();
double freq = ((rs1.getInt(2)) * 100 / count);
s = s + "['" + files + "', " + freq + "]";
}
String str = "[" + s + "]";
System.out.println(str);
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var string="<%=str%>
";
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {
'packages' : [ 'corechart' ]
});
google.setOnLoadCallback(drawChart);
// Set a callback to run when the Google Visualization API is loaded.
function drawChart() {
alert(string);
var data = google.visualization.arrayToDataTable();
data.addColumn('string', 'File name');
data.addColumn('number', 'percent');
data.addRows(string);
// Set chart options
var options = {
'title' : 'Chart View',
'width' : 400,
'height' : 300
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document
.getElementById('chart_div'));
chart.draw(data, options);
alert(str);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 400; height: 300"></div>
</body>
</html>

Ok, your problem is with this line:
var string="<%=str%>
";
It is converted to something like:
var string="['file1', 1, 'file2', 2...]
";
this is wrong, because it must be not String type, but array type. So, you have to remove double-quoutes and turn it to just:
var arrayData=<%=str%>;
...
data.addRows(arrayData);

Related

Responses of MS sql queries to different request are getting mixed on apache tomcat server

I have a web application whoses task is to show image and id no of employee based on events getting registered in MS SQL Data base. I'm selecting last(latest) event occurred for two inputs (readers) and showing image and id no of employees. I am refresing the web page every 500ms to update any new event with respect to the inputs(reader). When I am using only one client application works properly however with multiple clients (running parellel browsers with diffrent input (reader) selected) I am getting Image of other clients mixed.( i.e. Consider opening the url at two location and selecting input1 and 2 for one browser(1) and input 3 and 4 for other browser(2). Ideally browser(1) should show image only from input 1 & 2 and browser 2 should show images from input 3 & 4 But browser(1) is showing images of browser(2) and browser(2) shows images of browser(1) also.) Below is my web page code please suggest the solution.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.util.*" %>
<%# page import="javax.sql.*;" %>
<html>
<head>
<style>
table, th, td {
border:1px solid black;
border-collapse: collapse;
text-align: center;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PoP UP DISPLAY</title>
<script >
window.setInterval('refresh()', 800);
// Call a function every 800 milliseconds
// Refresh or reload page.
function refresh() {
window .location.reload();
}
</script>
</head>
<body style="background-color: black;">
<jsp:declaration>
String reader1 ="";
String reader2 ="";
String image1 ="";
String image2 ="";
String empCode1 ="";
String empCode2 ="";
String empName1 ="";
String empName2 ="";
</jsp:declaration>
<jsp:scriptlet>
reader1 = request.getParameter("reader1");
reader2 = request.getParameter("reader2");
</jsp:scriptlet>
<%
java.sql.Connection con1;
java.sql.Statement s;
java.sql.ResultSet rs1, rs2;
java.sql.PreparedStatement pst;
con1=null;
s=null;
pst=null;
rs1=null;
rs2=null;
// Remember to change the next line with your own environment
String url=
"jdbc:jtds:sqlserver://IP_Address_Of_DB/ DB_Name;instance= INSTANCEB";
String id= "user_id";
String pass = "user_pass";
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con1 = java.sql.DriverManager.getConnection(url, id, pass);
}catch(ClassNotFoundException cnfex){
cnfex.printStackTrace();
}
String sql1 = "select top 1 * from ecbacs.EventLog where ReaderId= '"+reader1+"' order by EventNo desc";
String sql2 = "select top 1 * from ecbacs.EventLog where ReaderId= '"+reader2+"' order by EventNo desc";
%>
<%
try{
s = con1.createStatement();
rs1 = s.executeQuery(sql1);
while( rs1.next() ){
empCode1= rs1.getString("EmpCode");
empName1= rs1.getString("CardHolderName");
}
s = con1.createStatement();
rs2 = s.executeQuery(sql2);
while( rs2.next() ){
empCode2= rs2.getString("EmpCode");
empName2= rs2.getString("CardHolderName");
}
image1 = empCode1+".png";
image2 = empCode2+".png";
%>
<table style="height:100%;width:100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0;border:1px solid">
<tr style="height: 95%;">
<td><img alt="Employee1 Photo" style="height: 100%" src="images/<%=image1%>"</td>
<td><img alt="Employee2 Photo" style="height: 100%" src="images/<%=image2%>"</td>
</tr>
<tr >
<td style="color:#ffffff; font-size: 2em"><%= empName1 %></td>
<td style="color:#ffffff; font-size: 2em"><%= empName2 %></td>
</tr>
</table>
<%
}
catch(Exception e){e.printStackTrace();}
finally{
if(rs1!=null) rs1.close();
if(rs2!=null) rs2.close();
if(s!=null) s.close();
if(con1!=null) con1.close();
}
%>
</body>
</html>
I am running the above applcation on Apache tomcat version 6. Please see the above code and help me with the solution. also is there any other way to achieve the above funtionality please suggest. I am a beginner with web programming also not from computer science background.

how to open a jasper report exporting to pdf in a new window

I have been exporting jasper report to pdf but it opens in the same window which is a problem to me because if i want to go to previous page i cant be able to go to previous page so i thought of opening pdf page in a new window but i dont have any idea of how to open it in a new window.
sample1.jsp
<%# page import="java.io.*"%>
<%# page import="java.sql.Connection"%>
<%# page import="java.sql.DriverManager"%>
<%# page import="java.util.HashMap"%>
<%# page import="java.util.Map"%>
<%# page import="net.sf.jasperreports.engine.*"%>
<%# page import="net.sf.jasperreports.engine.*" %>
<%# page import="java.text.SimpleDateFormat" %>
<%# page import="java.text.ParseException" %>
<%# page import="java.io.File" %>
<%# page import="java.io.FileInputStream" %>
<%# page import="java.io.FileNotFoundException" %>
<%# page import="java.io.InputStream" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.io.FileOutputStream" %>
<%# page import="java.io.ByteArrayOutputStream" %>
<%# page import="java.io.OutputStream" %>
<%# page import="java.util.HashMap" %>
<%# page import="java.util.Map" %>
<%# page import="net.sf.jasperreports.engine.util.*" %>
<%# page import="net.sf.jasperreports.engine.export.*" %>
<%#page import = "net.sf.jasperreports.engine.design.JRDesignQuery"%>
<%#page import = "net.sf.jasperreports.engine.xml.JRXmlLoader"%>
<%#page import = "net.sf.jasperreports.engine.design.JasperDesign"%>
<%#page import = "net.sf.jasperreports.view.JasperViewer"%>
<%#page import = "net.sf.jasperreports.engine.JRException"%>
<%#page import = "net.sf.jasperreports.engine.JRResultSetDataSource"%>
<%#page import = "net.sf.jasperreports.engine.JasperCompileManager"%>
<%#page import = "net.sf.jasperreports.engine.JasperExportManager"%>
<%#page import = "net.sf.jasperreports.engine.JasperFillManager"%>
<%#page import = "net.sf.jasperreports.engine.JasperPrint"%>
<%#page import = "net.sf.jasperreports.engine.JasperReport"%>
<%#page import = "net.sf.jasperreports.engine.data.JRCsvDataSource"%>
<%#page import = "net.sf.jasperreports.engine.export.ooxml.JRDocxExporter"%>
<%#page import = "net.sf.jasperreports.engine.export.JRPdfExporter"%>
<%# 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
Connection conn = null;
String cate=(String)session.getAttribute("cat");
String stat=(String)session.getAttribute("sta");
String dayy=(String)session.getAttribute("da");
String monthh=(String)session.getAttribute("mon");
String yearr=(String)session.getAttribute("yea");
String dayy1=(String)session.getAttribute("da1");
String monthh1=(String)session.getAttribute("mon1");
String yearr1=(String)session.getAttribute("yea1");
System.out.println("2 is:"+cate);
System.out.println("4 is:"+stat);
System.out.println("5 is:"+dayy);
System.out.println("6 is:"+monthh);
System.out.println("7 is:"+yearr);
System.out.println("8 is:"+dayy1);
System.out.println("9 is:"+monthh1);
System.out.println("10 is:"+yearr1);
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database","root","root");
String sql="select * from lead where Status='" + stat.replaceAll("\\'","''") + "'";
sql+=" AND Category='" + cate.replaceAll("\\'","''") + "'";
sql+=" AND DATE(Lead_Date)>='" + yearr + "-" + monthh + "-" + dayy + "'";
sql+=" AND DATE(Lead_Date)<='" + yearr1 + "-" + monthh1 + "-" + dayy1 + "'";
String jrxmlFile ="D:/dev/tools/jasper files/report3.jrxml";
InputStream input = new FileInputStream(new File(jrxmlFile));
JasperDesign jasperDesign = JRXmlLoader.load(input);
System.out.println("Compiling Report Designs");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
System.out.println("Creating JasperPrint Object");
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("sql",sql);
byte[] bytes = JasperRunManager.runReportToPdf(jasperReport, map, conn);
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
ServletOutputStream outStream = response.getOutputStream();
outStream.write(bytes, 0, bytes.length);
outStream.flush();
outStream.close();
}
catch(Exception e)
{e.printStackTrace();}
%>
</body>
</html>
view.jsp
<script type="text/javascript">
function setAction(nPage){
document.forms[0].action = nPage;
}
</script>
</head>
<body>
<form>
<%
String category=request.getParameter("category");
session.setAttribute("cat",category);
String status=request.getParameter("status");
session.setAttribute("sta",status);
System.out.println("status is:"+status);
String day=request.getParameter("day");
session.setAttribute("da",day);
String month=request.getParameter("month");
session.setAttribute("mon",month);
String year=request.getParameter("year");
session.setAttribute("yea",year);
String day1=request.getParameter("day1");
session.setAttribute("da1",day1);
String month1=request.getParameter("month1");
session.setAttribute("mon1",month1);
String year1=request.getParameter("year1");
session.setAttribute("yea1",year1);
%>
<select onchange="setAction(this.value)">
<option value=''> Make a selection </option>
<option value='sample1.jsp'> PDF</option>
<option value='XLS_LEAD.jsp'> XLS </option>
<option value='DOC_LEAD.jsp'> DOC </option>
<option value='XLSX_LEAD.jsp'> XLSX </option>
</select>
<br/>
<input type="submit" value="Submit">
</form>
</body>
Considering your view.jsp
I can see that you already have put all variables into the session you are only using the form to select to which page you need to go.
You can do something like this...
<script type="text/javascript">
function generateReport() {
var e = document.getElementById("idOfYourSelectYouNeedToAddedIt");
var strPage = e.options[e.selectedIndex].value;
window.open(strPage);
return false; //This make you stay on this page;
//return true; //Set the action tag in the form to the page you like to go to!
}
</script>
<form name="myForm" onsubmit="return generateReport()">
<select id = "idOfYourSelectYouNeedToAddedIt">
<option value=''> Make a selection </option>
..... the other option values
</form>
Note if you like to go to another page you can simple add action tag to your form tag and return true in the generateReport() function
example
<form name="myForm" action="thisIsWhereILikeToGo.jsp" onsubmit="return generateReport()">
Note: You should remove the onchange="setAction(this.value) code, it has no use anymore and consider checking that strPage is not empty, no selection...

Bring SQL data to jquery availabletag

I'm trying to make the autocomplete textbox, but how can i include SQL Data to jquery available tag and loop it? I failed to perform the function based on the following code. Any help would be appreciated! Thanks
This is my expected output : Expected Result Demo
Error on jquery code
My textbox only list the last row of data from database.
<%
String FRUIT_CODE = "";
String FRUIT_DESCP= "";
Vector vFruit = new Vector();
TEST.makeConnection();
String SQL = "SELECT CODE,DESCP FROM TB_FRUIT WITH UR";
TEST.executeQuery(SQL);
while(TEST.getNextQuery())
{
FRUIT_CODE = TEST.getColumnString("CODE");
FRUIT_DESCP = TEST.getColumnString("DESCP ");
Vector vRow = new Vector();
vRow.addElement(FRUIT_CODE);
vRow.addElement(FRUIT_DESCP);
vFruit.addElement(vRow);
}
TEST.takeDown();
%>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags =
[{
<%
String COMBINE = "";
String CODE2 = "";
String DESC1 = "";
for(int i=0;i<vFruit.size();i++)
{
Vector vRow = (Vector) vFruit.elementAt(i);
CODE2 = (String) vRow.elementAt(0);
DESC1 = (String) vRow.elementAt(1);
COMBINE += "\"" + CODE2 +" "+ DESC1 + "\",";
}
COMBINE = COMBINE.substring(0, COMBINE.length()-1);
//Combine result = "10000 Apple","20000 Orange", "30000 Mango", "40000 Banana"
%>
"value": <%=CODE2%>,
"label": <%=COMBINE%>
}];
$("#MODEL").autocomplete({
source: availableTags,
focus: function (event, ui) {
event.preventDefault();
$("#MODEL").val(ui.item.value);
}
});
});
</script>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="MODEL">
</div>
</body>
</html>
The scriptlet to generate availableTags does not add new object for each value in the vFruit Vector, only for the last one. It should be patched like this:
var availableTags = [
<%
String CODE2 = "";
String DESC1 = "";
for(int i=0;i<vFruit.size();i++)
{
Vector vRow = (Vector) vFruit.elementAt(i);
CODE2 = (String) vRow.elementAt(0);
DESC1 = (String) vRow.elementAt(1);
if (i > 0) out.print(",");
%>
{
"value": "<%= CODE2 %>",
"label": "<%= DESC1 %>"
}
<%
}
%>
];
$("#MODEL").autocomplete({
...
Btw. Why Vector and not e.g. ArrayList? Do you need a thread safe implementation here? It does not seem so.

return an arraylist from one jsp to another and give the json view

I have two jsp files,one is query.jsp and the other is b.jsp.In b.jsp i have connected a database,selected all values from database table testemployee and made an arraylist rows of all values inside public List select() function then returned the list.In query.jsp i tried to make the json format of that list calling select function of b.jsp
<% Gson gson = new Gson();
String json = gson.toJson(select()); %>
but it is not showing the json format of the database values.When i wrote
<%=select() %>
it was showing the database values list perfectly.How should i solve it?Please consider my question.
my code
query.jsp
<%#page import="com.google.gson.Gson"%>
<%#include file="b.jsp"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2><%
Gson gson = new Gson();
String json = gson.toJson(select());
// select()
%>
</h2>
</body>
</html>
b.jsp
<%!
Connection connection = null;
Statement statement = null;
String query;
%>
<%
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "postgres", "root");
statement = connection.createStatement();
} catch (Exception e) {
out.println(e.getMessage());
}
%>
<%!
public List select() {
List rows = new ArrayList();
Map row = null;
try {
query="select * from testemployee";
ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData metaData = resultSet.getMetaData();
int numColumns = metaData.getColumnCount();
while (resultSet.next()) {
row = new HashMap();
for (int i = 1; i < numColumns + 1; i++) {
row.put(metaData.getColumnName(i), resultSet.getObject(i));
}
rows.add(row);
}
resultSet.close();
} catch (Exception e) {
}
return rows;
}
%>​
i have imported all necessary files and also included b.jsp in query.jsp
<%= select() %> is an expression that converts whatever on the right part to a String, in this case the output of select method which is a List.
select() is a java method not a function
So in order to to view your list you need to iterate over it and draw it in a table, which means HTML otherwise you will be just executin a java method.
Here is an example.
EDIT :
<body>
<h2><%
Gson gson = new Gson();
String json = gson.toJson(select());
// select()
%>
<%=json%>
</h2>
</body>

New to d3, unable to show graph with json

I'm very very very new to d3, and I have a problem getting a line graph with json.
In my ReportBucketDAO.java, I generate out json with my database data.
while (rs.next())
{
String currency = rs.getString("currency");
Timestamp pointDateTimeTs = rs.getTimestamp("point_datetime");
String pointDateTime = pointDateTimeTs.toString();
pointDateTime = pointDateTime.substring(0, pointDateTime.indexOf('.'));
double pointValue = rs.getDouble("sum(`point_value`)");
org.json.JSONObject jobj = new org.json.JSONObject();
jobj.put("currency", currency);
jobj.put("pointDateTime", pointDateTime);
jobj.put("pointValue", pointValue);
jArray.add(jobj);
}
The json string is:
[{"pointValue":274,"pointDateTime":"2015-01-20 00:00:00","currency":"GBP"},
{"pointValue":571,"pointDateTime":"2015-01-20 00:00:00","currency":"SGD"},
{"pointValue":561,"pointDateTime":"2015-01-20 00:00:00","currency":"USD"}]
I also had a jsp called getVolumeData.jsp which allow me to save the above json to "data.json"
<%#page import="java.util.ArrayList"%>
<%#page import="com.ach.model.ReportBucket"%>
<%#page import="com.ach.model.ReportBucketDAO"%>
<%#page import="java.io.*"%>
<%#page import="org.json.simple.*"%>
<%
ReportBucketDAO rbDAO = new ReportBucketDAO();
JSONArray rbjson = rbDAO.retrieveByReportTypeJson();
System.out.println(rbjson);
request.setAttribute("rbJsonString", rbjson);
try {
FileWriter jsonFileWriter = new FileWriter("data.json");
jsonFileWriter.write(rbjson.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
%>
I call the d3 content within home.jsp content
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Project</title>
<link rel="shortcut icon" href="assets/img/tBank.ico">
<!-- Bootstrap core CSS -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<script data-require="d3#3.5.3" data-semver="3.5.3" src="assets/js/d3.js"></script>
<!-- Custom styles for this template -->
<link href="assets/css/dashboard.css" rel="stylesheet">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/script.js"></script>
<script>
$(function() {
$("#header").load("header.jsp");
$("#sidebar").load("sidebar.html");
//$("#d3content").load("getVolumeData.jsp");
});
</script>
</head>
<body>
<div id="header"></div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar" id="sidebar">
<!--Sidebar here-->
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<!-- <img id="loading" src="assets/img/ajax_load.gif" alt="loading" />-->
<div id="pageContent">
<!-- this is where our AJAX-ed content goes -->
<h1 class="page-header">My Dashboard</h1>
</div>
<div id="d3content">
<script type="text/javascript">
$("#d3content").load(function(event){
// Set the dimensions of the canvas / graph
var margin = {
top: 30,
right: 20,
bottom: 70,
left: 50
},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%Y-%m-%d %X").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var priceline = d3.svg.line()
.x(function(d) {
return x(d.pointDateTime);
})
.y(function(d) {
return y(d.pointTime);
});
// Adds the svg canvas
var svg = d3.select("#d3content")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Get the data
d3.json("data.json", function(error, data) {
data.forEach(function(d) {
d.symbol = d.currency;
d.pointDateTime = parseDate(d.pointDateTime);
d.pointTime = +d.pointValue;
});
console.log(data);
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.pointDateTime;
}));
y.domain([0, d3.max(data, function(d) {
return d.pointTime;
})]);
// Nest the entries by symbol
var dataNest = d3.nest()
.key(function(d) {
return d.symbol;
})
.entries(data);
console.log(dataNest);
var color = d3.scale.category10(); // set the colour scale
legendSpace = width / dataNest.length; // spacing for the legend
// Loop through each symbol / key
dataNest.forEach(function(d, i) {
console.log(d);
svg.append("path")
.attr("class", "line")
.style("stroke", function() { // Add the colours dynamically
return d.color = color(d.key);
})
.attr("id", 'tag' + d.key.replace(/\s+/g, '')) // assign ID
.attr("d", priceline(d.values));
// Add the Legend
svg.append("text")
.attr("x", (legendSpace / 2) + i * legendSpace) // space legend
.attr("y", height + (margin.bottom / 2) + 5)
.attr("class", "legend") // style the legend
.style("fill", function() { // Add the colours dynamically
return d.color = color(d.key);
})
.on("click", function() {
// Determine if current line is visible
var active = d.active ? false : true,
newOpacity = active ? 0 : 1;
// Hide or show the elements based on the ID
d3.select("#tag" + d.key.replace(/\s+/g, ''))
.transition().duration(100)
.style("opacity", newOpacity);
// Update whether or not the elements are active
d.active = active;
})
.text(d.key);
});
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
});
});
</script>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script data-require="bootstrap#3.3.1" data-semver="3.3.1" src="assets/js/bootstrap.min.js"></script>
<!--<script src="assets/js/docs.min.js"></script>-->
</body>
</html>
I wish the d3 to be loaded inside d3content, but it doesnt show/display anything, any help?
Here's the problems:
1.) You don't load d3.js
2.) Your variables aren't mapped correctly. In this block:
data.forEach(function(d) {
d.currency = +d.currency; // this is a string do not use +
d.pointDateTime = parseDate(d.pointDateTime);
d.pointTime = +d.pointTime; // your json is pointValue, not pointTime
});
3.) Your date parse function is wrong. Should be:
var parseDate = d3.time.format("%Y-%m-%d %X").parse;
Cleaning this up, produces this example.

Categories

Resources