I’m having a little trouble using jQuery in Rails.
I’d like to call the destroy method for a specific list item and then remove it from the list via ajax. My code is pretty simple:
# _web_profile.html.erb - The partial containing the link to destroy:
<%= link_to 'Remove', web_profile, :method => :delete, :class => 'remove_button' %>
# The ajax hijacking
$('.remove_button').live('click', function() {
$.ajax({ type: 'delete', url: this.href });
return false;
});
# In my controller
format.js { render(:update) { |page| page.remove "web_profile_#{id}" } }
Ok, basicly that’s it. When I press my button everthing works fine, but instead of executing the script I’m getting it a text output in the browser:
# Browser output
try {
jQuery("#web_profile_12").remove();
} catch (e) {
alert('RJS error:\n\n' + e.toString());
alert('jQuery(\"#web_profile_12\").remove();'); throw e
}
Any idea why this nice javascript code isn’t executed? I tried to add dataType to the ajax request already.
Thanks and best regards,
Joe
Why “type” is set to “delete”? It should be set to “POST” and dataType to “script”. Because of cross browser compatibility isssues, a workaround should be used to specify action as the RESTful delete. The data should have “_method” parameter set to “delete”.
I suggest to install jrails and use link_to_remote and other Rails helpers. They generate correct JS code. So you can learn how to build correct Rails Ajax requests.