Xeen
Xeen

Reputation: 7003

How to execute JS after redirect in a controller (Rails)?

Create

if @image.save
    format.html { redirect_to vote_path(@image) }
    format.js { render :js => "my_function();" }
end

so I'd like to fire up a function after the redirect has happened, but this doesn't work. Are there any other methods I could try and could you suggest me any please?

Thank you.

Upvotes: 2

Views: 1480

Answers (2)

JeanMatheus
JeanMatheus

Reputation: 17

An alternative would be to create a view to create.js.erb, and it run JS:

Your controller:

if @image.save
  format.html { redirect_to vote_path(@image) }
  format.js { }
end

create.js.erb

$("#share_window").show();

Upvotes: 0

hunterboerner
hunterboerner

Reputation: 1274

The redirect and render are separate. If you want it to run JS after the redirect, you can put some in the view that the vote_path is using. If you only want it to run after the redirect and not on the page load, you can set a flash before you redirect, and then check for the flash in the view.

Upvotes: 1

Related Questions