Petr
Petr

Reputation: 2099

How to respond_to js.erb?

I have this form with remote: true

<div id="new_review"></div>
<%= form_for @feedback, remote: true do |f| %>
  <%= f.text_area(:comment)" %>
  <%= f.submit("Submit") %>
<%end%>

It is going to this controller using ajax

def create
    @feedback = Feedback.new(feedback_params)
    respond_to do |format|
        @feedback.save
        format.html {}
        format.js {}
    end
end

I created a file create.js.erb in the feedbacks folder

$("#new_review").append("<h1>lallalalalala</h1>");
alert('js was called!'); 

On the server side the request is going through the controller and even rendering the create.js.erb - but nothing is happening.

Started POST "/feedbacks" for ::1 at 2016-03-04 18:43:29 +0100
Processing by FeedbacksController#create as JS
  Parameters: {"utf8"=>"✓", "feedback"=>{"comment"=>"dasd"}, "commit"=>"Submit"}
   (0.1ms)  BEGIN
  SQL (0.3ms)  INSERT INTO "feedbacks" ("comment", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["comment", "dasd"], ["created_at", "2016-03-04 17:43:29.277992"], ["updated_at", "2016-03-04 17:43:29.277992"]]
   (6.0ms)  COMMIT
  Rendered feedbacks/create.js.erb within layouts/application (0.1ms)
  Rendered layouts/_head.slim (31.2ms)
  Rendered layouts/_navbar.html.erb (0.1ms)
  Rendered layouts/_errors.slim (0.3ms)
  Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 58ms (Views: 48.9ms | ActiveRecord: 6.4ms)

Application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks

I was googling it the whole day, was watching tutorials but couldn't make it work. I tried things like $.ajaxSetup in application.js and some ajax requests but no luck.

How does it work? Would appreciate also some great tutorials for ajax, js or any tips. Thank you.

Thank you,

Upvotes: 1

Views: 2142

Answers (2)

Petr
Petr

Reputation: 2099

I found an answer to my question here.

I solved the issue with a line of code in my controller respond format.js by adding this line: {render layout: false}

Another solution might be adding data: {type: "script"} to your form_for, but in my case it didn't work.

The working controller looks like this:

def create
    @feedback = Feedback.new(feedback_params)
    respond_to do |format|
        @feedback.save
        format.html {}
        format.js {render layout: false}
    end
end

Thanks everyone for being involved.

Upvotes: 2

Andy Chong
Andy Chong

Reputation: 1

Yo, I'm not too sure, but try substitute

respond_to do |format|
        @feedback.save
        format.html {}
        format.js {}
    end

to this

respond_to :js

Upvotes: 0

Related Questions