Is there a way for me to call ruby on rails functions from within javascript?
For instance I have a partial => _micropost_form.html.erb and I want it to appear in a separate div when a button is clicked. I figured the best way to do that would be to use javascript. Currently I have:
document.getElementById("micropost").innerHTML=
So I’m pretty lost. I feel like this should be a pretty simple problem to work out though. Thanks!
EDIT:
So I have a link in my _header file:
<li>Add Content</li>
As well as a div:
<div id="popout"></div>
In my content controller I have a method:
def add_content
@content = Content.new
respond_to do |format|
format.html
format.js
end
As well as the file (located in views/contents) add_content.js.erb (_content_form is an html.erb file located in shared)
$('#popout').replaceWith("<%= escape_javascript render
(:file => 'shared/_content_form') %>");
I know the call I’m supposed to make in <li>Add Content</li> involves link_to however, I have yet to be able to get it to work correctly. The output to the console usually looks like a page refresh. Any help would be greatly appreciated!
In addition to the answer by ismaelga, I would like to add that if you have static HTML content in
_micropost_form.html.erbthen there’s no reason why that should be aerbfile or apartial. Having that content within ahidden divand then toggling that based on the button click would be a good solution.If, however, you have dynamic content in that file then your best bet is to use
AJAX. Some of the links provided by Felix Cling in the comments are a good starting point. I find myself using the following line of code in the.js.erbfile quite a bit though to achieve what you want to:Or, you could use the jquery append instead of replaceWith.