Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 422
ciembor Avatar asked Oct 16 '25 00:10

ciembor


1 Answers

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.

like image 170
vee Avatar answered Oct 17 '25 14:10

vee