1

I'm using Rails 4.0beta and I have the following d3.js script at the bottom of the body section. When pasted directly into the Chrome developer tools console, the code generates the graph. But if it is just as a script in the file that gets sent from the server to render the page, it doesn't generate the graph. Anyone know why? I must be making some simple mistake ... just can't figure out where.

<script type="text/javascript" src="http://d3js.org/d3.v3.min.js">
function generateGraph() {
    var margin = {top: 30, right: 20, bottom: 30, left: 50}, 
            width = 600 - margin.left - margin.right,
            height = 270 - margin.top - margin.bottom;

    var parseDate = d3.time.format("%d-%b-%y").parse; 

    var x = d3.time.scale().range([0, width]);
    var y = d3.scale.linear().range([height, 0]); 

    var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(5); 
    var yAxis = d3.svg.axis().scale(y).orient("left").ticks(5);

    var valueline = d3.svg.line().x(function(d) { return x(d.date); }).y(function(d) { return y(d.load_volume); });

    var svg = d3.select("body").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 + ")");

    d3.json("/users/5/workouts/analyze.json", function(error, data) {
    data.forEach( function (d) {
       d.date = parseDate(d.date);
       d.load_volume = +d.load_volume;
    });
        // Scale the range of the data
        x.domain(d3.extent(data, function(d) { return d.date; }));
        y.domain([0, d3.max(data, function(d) { return d.load_volume; })]);

        svg.append("path").attr("d", valueline(data));                                              // Add the valueline path
        svg.append("g").attr("transform", "translate(0," + height + ")") .call(xAxis);  // Add the X Axis .attr("class", "x axis")
        svg.append("g").attr("class", "y axis").call(yAxis);                                        // Add the Y Axis

    });
};

generateGraph();

</script> 
kwyoung11
  • 968
  • 1
  • 10
  • 31

2 Answers2

2

You are trying to include the library in the script tag that contains your code. Try to use this instead:

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
   // your code here
</script>
Pablo Navarro
  • 8,244
  • 2
  • 43
  • 52
0

Create another script tag inside body tag, and call the function from that script tag. i.e.

<script>
function generateGraph() {
// function definition 
}
</script>

<body>
<script>
generateGraph();
</script>
</body>
Avik
  • 739
  • 9
  • 15