views:

89

answers:

2

Hi guys,

I want to execute a simple thing. When the user clicks the link jQuery needs to generate an Ajax request which sends the id of the link item to a method in the controller. Basically I want a nice looking modal dialog window when the user clicks the delete link. That window needs to contain various info about the deleted items. E.g. <%= link_to "Delete", item, :id => "delete" %>

I'm able to select this link with jquery and even to open a popup dialog when the user clicks it. Through application.js but what i really need is jQuery to call my method when the link is clicked and in my method I would answer via format.js. In the js file I place the code to show modal dialog with required parameters. All those actions asynchonous via ajax ofcourse. I can't generate the ajax request to the method in the controller. Don't know already how to deal with the jQuery.ajax method, especially how to force jQuery to pass the url parameter to the rails method. I watched the railscast and studied the example with .post, but I don't need to submit any form. Any advise is appreciated. Thanks

+1  A: 

Rails expects a post, with a hidden param.

$('#delete').click(function(e){
  e.preventDefault();
  $.post($(this).attr('href'), { _method: 'delete' });
});
vise
Thanks, it was helpful!
Dennis
A: 

Rails 3 has an unobtrusive way of doing this using a jQuery plugin:

http://github.com/rails/jquery-ujs

Once you have that loaded into your layout (with jQuery 1.4.1 or newer), you can do interactions like this pretty easily.

<%= link_to 'delete', item, :remote => true, :method => :delete, 
       :confirm => 'Are you sure?' %>

In Rails 3 all this does is add some HTML attributes to your link. These get caught by live handlers in the jQuery plugin. It's easy to use this behavior in a Rails 2 application, though:

<%= link_to 'delete', item, :'data-remote' => true, :'data-method' => :delete, 
       :'data-confirm' => 'Are you sure?' %>

Note that you need to have the jQuery plugin loaded in your view.

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

If you need the initial response to be a modal instead of an alert, you could make the first link a bit simpler:

<%= link_to 'delete', modal_confirm_item_url(item), :'data-remote' => true %>

You could link it to some pre-existing member action. Or since you may eventually want to use .js responses from those actions to serve other ajax requests, it may make sense to create a new action to handle this behavior.

Eric Saxby