Home Telecommuncations Hosting Signup Articles
Contact Us Login


ENTERPRISE Rails Hosting

We provide Ruby On Rails web hosting for Australian websites who want a super fast website, with local Australian support which is available when you need it

order
Ruby On Rails Web Server
RUBY On Rails - HOWTO Show/Hide a Div Using AJAX

This is a simple article to demonstrate how easy, simple and effective it can be utilising the web2.0 functionality made simple in Ruby On Rails.

There are 4 steps to building a simple show/hide div.


1.

Include the Javascript libraries. This is best placed in your layout, so in a default project using the standard layout, open app/view/layouts/standard.rhtml. After the

<head>

Put the following:

<%= javascript_include_tag :defaults %>

2.

Build your form pieces. Firstly we need to define a form and an ajax action for that form. In this example I will be using a check box.
The following form belongs in a view and should look like this:

<% form_tag :action => "process_application" do-%>
      By checking this box, I agree to the terms and conditions.
      <%= check_box "customer_details", "accepted_terms" %>
      <%= observe_field(:customer_details_accepted_terms,
                        :on => :selected,
                        :update => :submit_div,
                        :url => { :action => :accepted_terms }) %>

        <div id="submit_div">
        </div>
  <% end -%>

So we have defined a observe_field which will fire a AJAX request to ':accepted_terms', which is an Action. If you change the form or objects, you will need to update the name of the field to observe (first field).
We have also specified the submit_div as the location for our returned information from the ajax request, which as you can see is blank by default. We plan to render a submit button so then can continue with the form once they select the check box.



3.

Now we open our controller and write the action 'accepted_terms' to make a decision if the check box is selected.

def accepted_terms
  if params["1"]
    render :partial => "submit_application_button"
  else
    render_text "You cannot continue without agreeing to the Terms and Conditions."
  end
end

So as this action executes it renders to our submit_div.



4.

In our controller we render a partial, so in your view directory, create a partial called: '_submit_application_button.rhtml'

<%= submit_tag "Submit Application" %>

This allows the user to actually submit the form specified in step 2.



There are other ways of using the ajax requests, you can add params by modifing the url section:

                        :url => { :action => :accepted_terms, :id => 4 }) %>

And there are much more possibilities, as I get more time to document them I will add to this article.

Need professional rails hosting in Australia?

All the articles are my intellectual property, If you would like to reproduce or add/remove anything please contact me before doing so.
Thanks
David Thomas