I have the following haml code:
%input{:value => "", :type => "button",:class => "SendBtn", :onclick => "$.get('#{send_path}',{parameter:$('#parameter').val()}); "}
This input executes an event in the controller.
// This is my controller
def send
if request.xhr?
// do stuff
end
end
But my js code in the corresponding .js.erb file is not being executed. It is returned as the response of the get request.
// send.js.erb
alert('hello');
How is the rails way to have this code executed?
Your problem is not Rails related, it’s jQuery. With the
getmethod you are just fetching more or less plain text. This will not get executed. You could do anevalon the text but there is a better way. Use thegetScriptmethod from jQuery. This will fetch and execute your code.As a side note, there are two things that are bothering me in your code:
data-attribute for your send path, like thisdata: { sendPath: send_path }, and retrieving it with$(yourInput).data('sendPath')in yourapplication.jsfile..jsfiles and communicate with the server over JSON.