Ruby, iOS, and Other Development

A place to share useful code snippets, ideas, and techniques

All code in posted articles shall be considered public domain unless otherwise noted.
Comments remain the property of their authors.


AJAX and Graphs

I just finished a post in which I promised some technical info about part of the site I worked on. This is more about JavaScript (and prototype) than it is about Rails, but I'm hitting the server for data, which means it's involved.

Consider a really simple CSS bar graph (with inline styles for blogging convenience):

Now suppose you wanted to update that graph via AJAX. The Rails way would be to use a prototype Ajax.Updater to replace the table with new HTML generated on the server side. That's workable, and easy to program, but it involves a larger payload from the server and more processing on the server side. All the client needs is the height of the bars, and the CSS change can be performed in JS. So consider a JS function (apologies for lack of highlighting; the syntax gem doesn't support JS):

function updateGraphs(req) {
  var data = eval('('+req.responseText+')');
  var bars = Element.getElementsBySelector('graph', 'td');
  if (data.length != bars.length) {
    alert("Length mismatch: there are "+
      bars.length+" bars and "+data.length+" returned heights.");
  for (var i=0;i<data.length;++i) {
    var height = data[i];
    var margin = 100-height;
        { height: ""+height+"px", "margin-top": ""+margin+"px" });

All you need back from Rails is an array of integers in JSON. You're all done in one line of Ruby/Rails:

render :text => @data.to_json, :type => "text/javascript"

A quick Ajax.Request with the proper parameters and the JS function above, and you're all set on the client side. To see a fancier version of this in action, look at this. If you haven't registered for the site, you'll need to do so through this link.


Update: We're using Flash now instead of the CSS graphs. Oh, well.

Labels: , ,


Post a Comment

Links to this post:

Create a Link

<< Home