Reputation: 2142
I have a Ruby method nested inside a jQuery onclick event and I want the method to execute when the div is clicked. This works; however, the method is also executing on page refresh. Why does it also execute on page refresh and is there any way to limit it to only onclick?
$(function() {
$('.myDiv').click(function(){
<% foo_bar %>
});
});
Upvotes: 0
Views: 220
Reputation: 26979
Please review this blog entry I wrote. In short, the ruby code executes on the server, and the javascript, which runs on the client, sees nothing. To have javascript interact with ruby, you need to initiate a request back to the server via some kind of ajax request. Libraries like jquery help with this.
Upvotes: 1
Reputation: 15010
I don't see how foo_bar
can be executed when you click on the div. Ruby is executed server side, jQuery is executed client side. You cannot execute ruby code from your client.
Your foo_bar
is executed on refresh page because the server need to interpret it to give it's result into the <% %>
tag. However, when you click on the div, nothing will happen because the jquery function will be empty (since you did not write <%= %>
). Even if you wrote <%= %>
, the jQuery would only execute the foo_bar
result, not the function itself.
Maybe you could explain what you want to do in your foo_bar
. If you want interact with the server, you will need something like Ajax
.
Upvotes: 3