This is basically javascript problem I am trying to get data by Ajax and put them into array but when I am logging the array in console I am getting Parse error. I am using d3.js library to create a dynamic graph. But the error is I guess purely due to Javascript concepts applied wrongly.
var n = 40,
random = function(){
d3.json("/server/file/path", function(graphdata){// This is the way we perform ajax call in d3,js
return graphdata;
});
},
data = d3.range(n).map(random);// Here I am putting into the array n = 40 elements obtained in the ajax call. But I am getting Parse error NaN for number values.
//Afterwards I am just drawing the graph
var margin = {top: 10, right: 10, bottom: 20, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, n - 1])
.range([0, width]);
var y = d3.scale.linear()
.domain([-1, 1])
.range([height, 0]);
var line = d3.svg.line()
.x(function(d, i) { return x(i); })
.y(function(d, i) { return y(d); });
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 + ")");
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
svg.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(y).orient("left"));
var path = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("path")
.data([data])
.attr("class", "line")
.attr("d", line);
tick();
function tick() {
// push a new data point onto the back
data.push(random());
// redraw the line, and slide it to the left
path
.attr("d", line)
.attr("transform", null)
.transition()
.duration(500)
.ease("linear")
.attr("transform", "translate(" + x(-1) + ")")
.each("end", tick);
// pop the old data point off the front
data.shift();
}
Thanks everyone.
As I was thinking it indeed was a JavaScript error, when tryng to bind the code to generate the graph with actual data coming from server the ajax call was fetching data a bit late. So the JavaScript interpreter was generating Parsing error since it expected the data values to be there but ajax being asynchronous could not yet manage to finish the data retrieval. Also I made some varaibles global variables to solve the problem.
My solution is as follows
})