Edward J. Stembler
Edward J. Stembler

Reputation: 2052

How to replace html using Rails 3 + jQuery?

I have several spinners on my page after database table names. Using jQuery on document ready, I want to replace those spinners with a count of the number of records in the individually listed table names.

For example, below, imagine the asterisk is a spinner:

Client Orders *

changes to:

Client Orders (125)

How would my jQuery code look in document ready?

<script type="text/javascript">
     $(document).ready(function() {
         $('#spinner1').html(/* ??? */);
         $('#spinner2').html(/* ??? */);
         $('#spinner3').html(/* ??? */);
  });
</script>

EDIT: Okay, let me word this differently... I have a helper function which accepts a table_name argument, and returns the output html . How do I call that function so that it runs after the page has loaded?

Upvotes: 1

Views: 2291

Answers (1)

Lucas Meyer
Lucas Meyer

Reputation: 679

The easiest/fastest way to do this is to create some new controller actions with html.erb templates, then to use jquery's load() function. So:

First, create a new action that outputs (using an .html.erb template) the HTML you want to display after documentReady. Make sure that your controller doesn't use layouts for the action, and create a named route that links to the action. Since you've already got the helper functions written, the template should just call your helper function with the appropriate arguments.

So, if your controller is called 'Users', and your new action is called 'ajax_info', you would create a new route called user_ajax_info, and link it into 'users/ajax/info'. If you went to user/ajax/info in the browser, you'd see the content (and only the content) you wanted to plug into your document using AJAX.

You can then load the content on document ready using Jquery's load(), eg:

<%= javascript_tag do %>
  $(document).ready(function() {
    $('spinner1').load('<%= user_ajax_info_url -%>');
  });
<% end %>

Rails will then automatically pass the correct URL for user_ajax_info to Jquery; Jquery will load the content at that URL, and replace the content of spinner1 with the new content. See http://api.jquery.com/load/ for more details.

Note that technically, this is probably not best practice; it would be a lot better (from a practices point of view) to return the data using XML/JSON. On the other hand, that's also a lot trickier to implement; I'd recommend starting with this, and then updating later if it becomes necessary.

Upvotes: 2

Related Questions