Harry Seldon's blog

Psychohistory on Rails

Read

A Rails/OFC/Ajax raw example

Posted by Harry Seldon on September 27, 2008

Here is a simple exercise to use Rails, OFC, OFC rails plugin and ajax together. The idea is just to follow the example given here in php. At first I did not manage to get this working. That is why I asked some help to Pullmonkey. He did a great job to make this working in this nice post . Moreover, he came up with nice improvements on OFC to render a chart using ajax and using Rails helper to keep a pretty code (you need to update OFC plugin to make his example work). However I want to show you here the translation in Rails of Teethgrinder’s tutorial with minimum code (no need to update OFC plugin).

Controller code (test_it_controller.rb), notice it has the original php code from teethgrinder in it.

class TestItController < ApplicationController
def tuto_5
    title = Title.new("tuto_5")
    #$title = new title( date("D M d Y") );
    #$chart = new open_flash_chart();
    @chart = OpenFlashChart.new
    #$bar = new bar();
    bar = BarGlass.new
    #$bar->set_values( array(9,8,7,6,5,4,3,2,1) );
    bar.set_values([1,2,3,4,5,6,7,8,9])
    #$chart->set_title( $title );
    @chart.set_title(title)
    #$chart->add_element( $bar );
    @chart.add_element(bar)
end
end

Then I had directly coded the view code (tuto5.html.erb) without helpers (and quite ugly) :

<head>
<script type="text/javascript" src="/javascripts/json2.js"></script>
<script type="text/javascript" src="/javascripts/swfobject.js"></script>
</head>

<body>
<script type="text/javascript">
swfobject.embedSWF("/open-flash-chart.swf", "my_chart", "350", "200", "9.0.0");
</script>
<script type="text/javascript">

function ofc_ready()
{
    alert('ofc_ready');
}

function open_flash_chart_data()
{
    alert( 'reading data' );
    return JSON.stringify(data);
}

function findSWF(movieName) {
  if (navigator.appName.indexOf("Microsoft")!= -1) {
    return window[movieName];
  } else {
    return document[movieName];
  }
}

var data = <%= @chart.to_s %>;
</script>

<p>Hello World</p>
<div id="my_chart"></div>
</body>

In this example you need the json2.js library that you can find here. However notice that Pullmonkey uses directly the json capabilities of Rails which is a much better way.
This code works, you can check it out here.

Thanks to Pullmonkey ! H

Posted in | no comments | Tags , , , , | atom

Delicious Add to Technorati Favorites Slashdot Sphere: Related Content

Trackbacks

Use the following link to trackback from your own site:
http://harryseldon.thinkosphere.com/trackbacks?article_id=rails-ofc-ajax-tuto-5&day=27&month=09&year=2008

Comments

Leave a response

Leave a comment

Markdown enabled

Search