Rails Ajax Eample


Overview

This is an example of how you can render a chart with ajax, following the usual Rails ajax workflow.


Example

To see this in action, please click on the "Get Ajax Chart" button below.


Code

The form code above that's been used to generate the chart via ajax.

  <%= form_tag("/docs/rails_ajax_chart", remote: true) do  %>
    <%= submit_tag "Get Ajax Chart" %>
  <%- end %>

Based on the above example, we need a controller action that returns a chart at controller#rails_ajax_chart.

  # In controller#rails_ajax_chart

  data_table = GoogleVisualr::DataTable.new
  data_table.new_column('string', 'Year')
  data_table.new_column('number', 'Sales')
  data_table.new_column('number', 'Expenses')
  data_table.add_rows(
    [
      ['2004', 1000, 400],
      ['2005', 1170, 460],
      ['2006', 660, 1120],
      ['2007', 1030, 540]
    ]
  )

  opts   = { width: 400, height: 240, title: 'Company Performance', hAxis: { title: 'Year', titleTextStyle: { color: '#FF0000' } } }
  @chart = GoogleVisualr::Interactive::AreaChart.new(data_table, opts)

Then, we'll render the chart with the render_js method in the view rails_ajax_chart.js.erb.

Unlike render_chart, render_js generates JavaScript without the script tag, and can be used within a JavaScript file.

  // In rails.ajax_chart.js.erb

  $("form").append("<div id='chart'></div>");
  <%= render_chart @chart, "chart", script_tag: false %>