0

I have a pretty standard Rails HAML new object form that does the usual stuff and ends with:

= f.submit "Add scenario"

This works perfectly, and the scenarios_controller.rb is also a straightforward:

def create
  ...create scenario...
  redirect_to scenarios_path
end

However, I have also developed a wizard-type form that needs to do some JavaScript on pressing my button:

= f.submit "Add scenario", :onclick => "return validateForm()"

In my CoffeeScript, I collect up all the information and finish up with:

$.post(
  url
  data
  (data, textStatus, jqXHR) ->
    # How do I follow the redirect?
return false

My url and data are correct as the above controller works correctly and creates my object, but my page doesn't redirect to scenarios_path. I think I should be doing something with the post result, but searching around the web I cannot find out what, and examining the returned fields in Chrome's debugger doesn't suggest anything. The only suggestion I saw was to use data.redirect, but such a field doesn't exist, although jqXHR.responseText seems to contain the page I want to redirect to.

2
  • You can redirect using javascript with window.location.href = "http://www.example.com"; Commented Dec 12, 2013 at 6:17
  • @cantonic I wanted to avoid that as my page takes a little time to render, so doing it twice seems a bit of a waste. Commented Dec 12, 2013 at 6:57

1 Answer 1

2

I'd treat the HTML call to Scenario#create and the JS call to Scenario#create differently, using a respond_to block.

In your scenarios_controller.rb file:

def create
  # create your object
  respond_to do |format|
    format.html do
      redirect_to scenarios_path
    end
    format.js
  end
end

In views/layouts/scenarios/create.js.erb, then put something like:

window.location.replace("<%= scenarios_path %>");

When you call Scenario#create with JS, the create.js.erb file gets rendered and forces the redirect. When you call Scenario#create with HTML, the redirect_to call happens as usual.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, that fixes the problem - the format.js was the magic I was missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.