Topic: Ajax basics by utilizing jQuery

Hi. I've been playing with Rails for some time, but have just until recently learning javascript in the form of jQuery. I assumed that nowadays the correct way to use jQuery in Rails app is through jquery-rails gem.

So, I'm building a simple app, where I'm getting an input from user, then do some manipulations on the input in the backend (a library under 'lib'), and show the output using jQuery. What is the correct way to achieve this, i.e. where shall I put my javascript code (should I create js.erb template under 'views' or just plain javascript under 'public/javascripts') and what kind of controller code do I need?

I haven't found any good guides about Rails and jQuery..

Re: Ajax basics by utilizing jQuery

Currently I have following code:

In site/convert.js.erb:

$('#decimal_converted').text("<%= @decimal %>");
$('#hexadecimal_converted').text("<%= @hexadecimal %>");
$('#binary_converted').text("<%= @binary %>");

In site_controller.rb:

class SiteController < ApplicationController

  def index
  end

  def convert
    number = params[:number]
    from = params[:radix]
    @decimal = Converter::convert(number, from.to_i, 10)
    @hexadecimal = Converter::convert(number, from.to_i, 16)
    @binary = Converter::convert(number, from.to_i, 2)
  end

end

In routes.rb:

Conversions::Application.routes.draw do
  root :to => 'site#index'
  post 'site/convert'
end

In site/index.html.erb:

    <%= form_tag '/site/convert', :id => 'conversion', :remote => true do %>
        <%= radio_button_tag 'radix', 10, true %> Decimal
        <%= radio_button_tag 'radix', 16 %> Hexadecimal
        <%= radio_button_tag 'radix', 2 %> Binary
        <%= number_field_tag 'number', '', :size => '20', :min => 0 %>
        <%= submit_tag 'Convert' %>
    <% end %>

    <table>
      <thead>Conversions</thead>
      <tr>
        <th>Decimal</th>
        <th>Hexadecimal</th>
        <th>Binary</th>
      </tr>
      <tr>
        <td id="decimal_converted"></td>
        <td id="hexadecimal_converted"></td>
        <td id="binary_converted"></td>
      </tr>

    </table>

When I try to submit the form, I get complained that "Missing template site/convert with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths "/home/alucard/sivut/conversions/app/views""

So what do I need to get the js.erb template working properly?

Last edited by Valafar (2011-03-25 07:21:26)