user12280951
user12280951

Reputation:

How redirect from controller side after Ajax call in Rails 6?

I want to know if it's possible to redirect with controller from an ajax request in Rails 6 ?

I tried to use

redirect_to "url"; return and render :js => "window.location.reload" don't work for me :(

Thank you for your help :)

Upvotes: 0

Views: 687

Answers (2)

PlatypusMaximus
PlatypusMaximus

Reputation: 74

Do it in your controller.

render js: "window.location='#{goal_path(@goal)}';"

Ideally you'll want to keep as much business logic out of your JS as possible for rails apps. You also can't cleanly use your route helper methods in js. You can however setup your "redirect" in your controller.

app/view/controllers/goals/adopt_controller.rb

# :nodoc:
class Goals::AdoptController < ApplicationController
  def update
    # business logic....

    # "redirect" the client 
    render js: "window.location='#{goal_path(@goal)}';"

    # or make a reusable js view. this will search a wide variety of possible file names. In this case it'll match /app/view/appliation/redirect.js.erb
    # @to = goal_path(@goal)
    # render 'redirect'

    # the above lets rails guess what you want to do. this is a bit more explicit to only render this view is the client can accept a js response. Other scenarios will throw an error
    # @to = goal_path(@goal)
    # respond_to do |format|
    #   format.js { render 'redirect' }
    # end
  end
end

/app/view/appliation/redirect.js.erb

window.location='<%= escape_javascript to %>';

Upvotes: 0

B-M
B-M

Reputation: 1308

This works for me:

window.location.href = '/path'

Example:

$.ajax({
    url: uri,
    type: "POST",
    data: form,
    dataType: 'json',
    processData: false,
    contentType: false
}).done(function(e) {
  window.location.href = '/project_proposals'
})

Upvotes: 1

Related Questions