Jeff
Jeff

Reputation: 4423

Rails redirect_to after jquery $.post

Why won't my browser go to the new page when I submit?

In my view I have a button that posts data to and action in my controller.

my coffee script:

$.post "/token/create", json

TokenController#create

redirect_to root_path, notice: 'Parser was successfully created.' 

The log file looks like it works:

Started POST "/token/create" for 127.0.0.1 at 2014-10-08 10:27:39 -0400
Processing by TokenController#create as */*
...
Redirected to http://localhost:3000/
Completed 302 Found in 37ms (ActiveRecord: 10.0ms)


Started GET "/" for 127.0.0.1 at 2014-10-08 10:27:40 -0400
Processing by VisitorsController#index as */*
...
Completed 200 OK in 2891ms (Views: 2886.6ms | ActiveRecord: 3.0ms)

But the page I am on is not changing. How do I make the page go to whatever page I specify in the "redirect_to" line?

Upvotes: 2

Views: 1115

Answers (2)

MrYoshiji
MrYoshiji

Reputation: 54882

You can do like the following:

def create
  # do some stuff
  if request.xhr? # test if the request is an AJAX call
    render js: "document.location = '#{root_path}'"
  else
    redirect_to root_path, notice: 'Parser was successfully created.' 
  end
end

You want to use flash also in the AJAX cases? check this answer: https://stackoverflow.com/a/18443966/976775 (and be nice, vote up his answer if it helps you)

Upvotes: 3

Fer
Fer

Reputation: 3347

Because you are performing an ajax call. You have to change the document.location via javascript as a response

create.js.erb

document.location = <%= root_url.inspect %>

for instance

Upvotes: 0

Related Questions