0

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 :)

  • The question isn't specific. Say you receive an AJAX request, do you want to redirect the user to another page? Or do you want to redirect the AJAX request to another route? If this is about the former, have you already looked at [How do I redirect to another webpage?](https://stackoverflow.com/q/503093/3982562) – 3limin4t0r May 25 '20 at 17:04

2 Answers2

1

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'
})
B-M
  • 1,248
  • 9
  • 19
0

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 %>';