Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 371
Galaxy Avatar asked Apr 01 '12 09:04

Galaxy


1 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.

like image 139
Yanhao Avatar answered Sep 27 '22 18:09

Yanhao