Redirect to after successful ajax form

I've got a form with remote => true. And right now my controller looks like:

  # POST /items
  # POST /items.json
  def create
    @item = @store.items.build(params[:item])

    respond_to do |format|
      if @item.save
        format.html { redirect_to edit_admin_item_path(@item), :flash => {:success => "#{@item.name} was successfully created."} }
        format.js { render :js => "window.location.href = ('#{edit_admin_item_path(@item)}');"}
        format.json { render json: @item, status: :created, location: @item }
      else
        format.html { render action: "new" }
        format.js { render :partial => 'fail_create.js.erb', :locals => { :ajax_errors => @item.errors.full_messages } }
        format.json { render json: @item.errors, status: :unprocessable_entity }       
      end
    end
  end

Which works but feels very clumsy. It also doesn't allow me to use a flash notice, which is sad time indeed.

Ideally I feel like I should be able to simply use "format.js { redirect_to...} or check against the request headers and redirect_to. Sheesh!

I'm not sure what the best solution is. Any advice would be super awesome, thanks in advance!

-- PS -- I know this has been asked somewhat before but to no avail: How to redirect after a successful AJAX form submission. There seems to many questions similar floating around, but no real solutions.

Answers


I think it might be impossible. The response to a Ajax request is processed by XMLHttpRequest. If a 3xx response is returned, XMLHttpRequest will follow the redirect itself, if the URL is of same origin. No matter how you set the headers, the browser cannot be aware of that. So the only way could be changing window.location with some Javascript.


Need Your Help

Moving a node and it's related siblings into a new parent

xml xslt xslt-1.0

I'm attempting copy an element and it's related siblings (where they exist in such an order) into a new shared parent but I'm struggling to do this - my XSLT knowledge is limited.

generic adder "inference architecture": simulation error

vhdl xilinx modelsim inference

So, I have to create a generic N-bit adder with carry in and carry out.