Hi, here are the steps to get anchors working by hijacking their behaviour with jQuery style.
In the view, lets call it index.html.erb
you put some anchor with a special id or class by using the normal link_to
helper - for example link to the show
action of the users controller by using the resource routing:
# in index.html.erb
<%= link_to 'First user', user_path(1), class => 'ajax_link' %>
<div id='some_container'>
to modify via javascript.
</div>
Second step - make the controller able to answer in javascript:
# in users_controller.rb
def show
@user = User.find(params[:id])
respond_to do |wants|
wants.html
wants.js
end
end
Next one - create the corresponding js.erb file, in this case it would be users/show.js.erb
and do all your javascript magic right here.
# show.js.erb
alert('ajax answers!');
$('#some_container').html('hey this works great');
$('#some_container').after("<%= @user.name %>");
Please note, that erb code has to be put into double quotation marks.
And now, on the last step, hijack the link with jQuery in your application.js
file like so:
# in application.js
$(document).ready(function () {
$(".ajax_link").live("click", function() {
$.getScript(this.href);
return false;
});
}
It's pretty simple: if your document is loaded completely, all nodes with the 'ajax_link' class are hijacked and on a click event getScript
gets the javascript answer from the url specified in the anchors href attribute.
By the way: this will also work perfect as normal link if javascript is disabled.
Hopes this will help you, if you have any questions don't hesitate to ask! ;)