views:

1837

answers:

2

Hey there,

is it somehow possible to call a rails function or to access a rails object from within jQuery? I'd like to do something like:

jQuery(document).ready(function($) {
$('#mydiv').html("<%= @object.name %>");
});

OR

jQuery(document).ready(function($) {
$('#mydiv').html("<%= render :partial => "contacts" %>");
});

At the moment I'm keeping all my jQuery stuff in my application.js, which is included in my layout. Oh yeah....and I'm not using Rails Edge.

Regards,

Sebastian

+2  A: 

You'll have to have a method in the controller that will render what you need, if you want to do that. Another way to do it is to use view blocks, like in the end of your layout view

<script type="text/javascript">
<%= yield :footerjs %>
</script>

and in the view do something like:

<% content_for :footerjs do %>
jQuery(document).ready(function($) {
$('#mydiv').html('<%= escape_javascript(render :partial => "contacts") %>');
});
<% end %>

You'll need to make sure that the partial you'll be rendering won't have characters that may cause javascript errors (like finishing the quotes before the end of the string, etc). Also, some browsers don't like multi-line strings, so you'll have to fiddle with that as well.

changelog
A: 

@changelog: thx a lot for your answer.

The problem depicted below the line was solved by enclosing the <%= yield :myjs %> in the appropriate javascript tags as follows:

<script type="text/javascript">
<%= yield :myjs %>
</script>

Thanks again!!


I tried to implement it the way you said, but I'm having some difficulties:

I put the following content_for block at the top of my show.html.erb:

<% content_for :myjs do %>
jQuery(document).ready(function($) { alert('hello'); });
<% end %>

In my layout.html I include all javascript as follows (here applications.js implements some general jQuery functions):

<head>
...
<%= javascript_include_tag 'jquery', 'application' %>
<%= javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? %>
<% yield :myjs %>
</head>
<body>
...

The problem is that my javascript doesn't show up in the page's source when I call it. Also the alert function is not called. When I put in <%= yield :myjs %> instead (with the =) the javascript is rendered at the beginning of my body block, instead of the head, but still the alert function isn't called when I open the page.

Sebastian
Sorry for the issues. I'll fix my answer for future reference. Glad I could help.
changelog