How to render only js without html (template, layout) in Rails

I have controller Message_Controller and this Controller has method "message" in this method i wanna render .js.erb file i need call js function from rails controller.I need reneder it without html-template(layout) just only js-code in this code i will call js-function with args .How to make it ??

My routes:

 post 'chat_bot/message', to: 'chat_bot#message'

My controller:

class ChatBotController < ApplicationController
     layout false

    def message
         #gon.watch.message = params[:text]
        @message = params[:text]
            puts @message
        render partial: 'message.js.erb', layout: false
    end


end

my message.js.erb file

alert('<%=@message %>');

Upvotes: 0

Views: 1748

Answers (2)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

With

render partial: 'message.js.erb', layout: false

Rails is going to look for a partial called _message.js.erb right in the folder responding to that controller.

You can use respond_to and there specify the format and what to render:

def message
  respond_to do |format|
    format.html { render partial: 'message.js.erb' }
  end
end

You can skip the instance variable assignation if you prefer, as you have access to the params within the request.

If your idea is to "evaluate" the alert, then it still should be inside a script tag:

<script>
  alert("<%= params[:text] %>");
</script>

Upvotes: 1

Kamal Pandey
Kamal Pandey

Reputation: 1598

just update it with

def message
  @message = params[:text]
  respond_to do |format|
     format.js
  end
end

Upvotes: 0

Related Questions