0

I have a form that creates messages in my view, and I want the list of messages on the same page to update on create. So I am using Ajax. The return from the create action seems to be html, and not just the js script, and the script is not executing. (I tried putting in an alert function to test).

Instead the script is appended to the end of the response. What am I doing wrong?

My controller action:

def create
    @order = Order.find(params[:order_id])
    @customer = @order.customer
    @message = current_user.messages.create(
      body: message_params[:body],
      order_id: @order.id
      )
    respond_to do |format|
      if @message.save
        format.html { redirect_to @message, notice: 'Message was successfully created.' }
        format.js
      end
    end

create.js.haml:

%script(type="text/javascript")
  $("#messages").append("<p>Hello</p>");

My form

= simple_form_for :message, remote: true, url: order_messages_path(@order), method: :post do |f|
  = f.error_notification
  = f.hidden_field :customer_id, value: @order.customer.id
  .form-inputs
    = f.text_field :body
  .form-actions
    = f.button :submit

And the response comes back with the full html:

  (...)
  </head>
  <body>
    <nav>
      (...)
    </nav>
    <script type='text/javascript'>
      $("#messages").append("<p>Hello</p>");
      console.log("Hello");
    </script>
    </div>
  </body>
</html>

Server response:

Started POST "/orders/1/messages" for 127.0.0.1 at 2015-07-15 21:48:31 +0200
Processing by MessagesController#create as JS
  Parameters: {"utf8"=>"✓", "message"=>{"customer_id"=>"1", "body"=>"There is a light."}, "commit"=>"Save Message", "order_id"=>"1"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Order Load (0.3ms)  SELECT  "orders".* FROM "orders" WHERE "orders"."id" = $1 LIMIT 1  [["id", 1]]
  Customer Load (0.3ms)  SELECT  "customers".* FROM "customers" WHERE "customers"."id" = $1 LIMIT 1  [["id", 1]]
   (0.2ms)  BEGIN
  SQL (0.8ms)  INSERT INTO "messages" ("body", "order_id", "creator_type", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["body", "There is a light."], ["order_id", 1], ["creator_type", "user"], ["user_id", 1], ["created_at", "2015-07-15 19:48:31.996217"], ["updated_at", "2015-07-15 19:48:31.996217"]]
   (1.2ms)  COMMIT
  Rendered messages/create.js.haml within layouts/application (3.6ms)
  Rendered layouts/_navigation.haml (1.4ms)
Completed 200 OK in 463ms (Views: 453.0ms | ActiveRecord: 3.2ms)
Paul Byrne
  • 1,563
  • 18
  • 24

1 Answers1

0

First of all, I think the %script(type="text/javascript") is not necessary. Try removing it and putting

format.js { render "create.js.haml" }

The #messages element exists, right?

Diego Garcia
  • 369
  • 2
  • 4