7
votes

Can't get an ajax form_for to respect the format.js respond_to only responds with format.html. Any help much appreciated.

view

This view is called in partial by AJAX and then the user submits the form. Could the initial ajax call confuse the 'remote:true' of this form?

<%= form_for([@nested, @nested.resources.new], remote: true) do |i|%>
  <%= i.hidden_field :inviter_id, value: current_user.id %>
  <%= i.hidden_field :fb_pic_url, value: f['pic_square'] %>
  <%= i.hidden_field :name, value: f['name'] %>
  <%= i.hidden_field :uid, value: f['uid'] %>
  <%= i.submit "Invite", class:"btn btn-success invite_button" %>
<% end %>

routes.rb

resources :nested do 
  resources :resources
end

controller

def create
  code code code

  respond_to do |format|
    format.html { redirect_to @nested, notice: "Successfully Posted Nested" }
    format.json { render json: @nested, status: :created, location: @nested }
    format.js { render :nothing => true }
  end
end

create.js.erb Present but empty

application.html

<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>

application.js

//= require jquery
//= require jquery_ujs
1
What accept headers are sent in the request?joshuacronemeyer
"HTTP_ACCEPT"=>"text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8"ajbraus
I don't understand the problem. You are saying that after submit form_for you are getting html response?jizak
Correct, it should be receiving a js request and responding with the js template from the format.js line but instead it is receiving an html request and giving an html response.ajbraus
@ajbraus, I'm having the same exact problem as you are even after following the instructions of the answer below without success. Did you get this working? Was it really just making the changes suggested in the answer below?Jake Smith

1 Answers

2
votes

Make sure you have the rails built-in non-intrusive jquery plugin included, since its responsible for making the remote: true code work.

also, if you want to render the template create.js.erb you need to leave the row format.js without a block:

respond_to do |format|
  ...
  format.js
end

Besides that, are you using the other response formats? json and html? if not, try to avoid putting them.