Callback after Rails link with data-remote="true" and data-method="PUT"

7.2k views Asked by At

I have this ruby code:

link_to t("general.actions.#{ action }"), [action, @app, item], { 
   :method => :put, 
   :remote => true, 
   :onclick => '$(this).closest("tr").find("td").fadeOut()' 
}, :class => 'status' 

which generates this html:

<a href="/apps/guess-the-model/contents/52118140d644363dc4000005/approve" 
   data-method="put" 
   data-remote="true" 
   onclick="$(this).closest("tr").find("td").fadeOut()" 
   rel="nofollow">
    approve
</a>

The problem is, i shouldn't use onclick. I should call this js code only if the AJAX is successfull, so I should somehow pass a callback and check XMLHttpRequest status. How can I do that using :remote => true and :method= :put?

2

There are 2 answers

0
vee On

With remote: true, Rails makes an ajax call to your controller action with format js. So, in your controller's action when you're ready to render the output you just need to specify format.js option as follows:

def action
  ...

  respond_to do |format|
    format.html {...} # You probably have something like this already
    format.js {} # Add this line
end

Then, you need add a action.js.erb file in your app/views/app/ directory and execute the javascript code that you wanted to execute on onclick there.

0
mridula On

You could also use the 'ajax:success' hook in your javascript like so:

jQuery

$('a.status').on('ajax:success', function(ev) {
    $(this).closest("tr").find("td").fadeOut()
})

Coffee

$ ->
    $("a.status").on "ajax:success", (event) ->
    //your code

And remove the onclick attribute of your link.