Can anyone help with how to use a jQuery get(json, txt, xml, whatever) and setInterval (d3.js) so that I can update my d3 bar chart every N seconds?
Or does anyone know of an example out there that uses a RESTful get to update data through setInterval in d3 SVGs?
I’ve read this tutorial all day, but not clicking with how to incorporate json instead of random walk.
Many Thanks in advance….
My Unsuccessful Attempt:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title> Testing a d3.js Walking Bar Chart via jQuery getText and d3.js setInterval </title>
<script type="text/javascript" src="http://localhost:8080/dev_tests/d3/d3.js"></script>
<script type="text/javascript" src="http://localhost:8080/dev_tests/latest.jquery/jquery-latest.js"></script>
</head>
<body>
<div class="body">
<div class="content">
<style type='text/css'>
.chart {
margin-left: 42px;
}
.chart rect {
fill: steelblue;
stroke: white;
}
</style>
<script type='text/javascript'>
var t = 1297110663,
v = 70,
data = d3.range(33).map(next1);
function next1() {
$.get('http://localhost:8080/dev_tests/data/file.txt', function(data1) {
$('.result').text(data1);
alert(data1);
return {time: ++t, value: v = data1 };
});
}
var w = 20,
h = 80;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, w]);
var y = d3.scale.linear()
.domain([0, 100])
.rangeRound([0, h]);
</script>
<p>Et voila!</p>
<script type='text/javascript'>
var chart3 = d3.select(".content").append("svg")
.attr("class", "chart")
.attr("width", w * data.length - 1)
.attr("height", h);
chart3.append("line")
.attr("x1", 0)
.attr("x2", w * data.length)
.attr("y1", h - .5)
.attr("y2", h - .5)
.style("stroke", "#000");
redraw3();
function redraw3() {
var rect = chart3.selectAll("rect")
.data(data, function(d) { return d.time; });
rect.enter().insert("rect", "line")
.attr("x", function(d, i) { return x(i + 1) - .5; })
.attr("y", function(d) { return h - y(d.value) - .5; })
.attr("width", w)
.attr("height", function(d) { return y(d.value); })
.transition()
.duration(1000)
.attr("x", function(d, i) { return x(i) - .5; });
rect.transition()
.duration(1000)
.attr("x", function(d, i) { return x(i) - .5; });
rect.exit().transition()
.duration(1000)
.attr("x", function(d, i) { return x(i - 1) - .5; })
.remove();
}
setInterval(function() {
data.shift();
data.push(data);
redraw3();
}, 3500);
</script>
</div>
</div>
</body>
</html>
jQuery’s ajax functions are asynchronous, so
next1()isn’t returning anything. You want to:push()it onto the data arrayYou can simulate this without a JSON call by doing this:
And when you get that working, switch to this:
One problem with this, though, is that if any of the JSON requests take longer than a second you could end up with data loading out of order. So it’s best to use
setTimeout()and queue up the next load only after you’re done with the previous one:Make sense?