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!
make it appear in an iframe:
function appear_it() {
document.getElementById("micropost").innerHTML = "<iframe id="micropostframe" src="bla/whatever.html"></iframe>";
}
Then you can style it with css.
Have a button or a link with the attribute onclick="appear_it();return false".
I think for what you are trying to achieve, rendering that "div" on the request as hidden and then the link trigger a js function to show it.
This should be a good solution unless that "link" brings some conditionals for what you want to render, for example if there is only one thing to display or else if you have many links to show at same div different content depending on the link you click. If the second case is the one you are trying to solve, you should really check ajax calls. Btw JQuery is your friend for this kind of stuff.
In addition to the answer by ismaelga, I would like to add that if you have static HTML content in _micropost_form.html.erb
then there's no reason why that should be a erb
file or a partial
. Having that content within a hidden div
and 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.erb
file quite a bit though to achieve what you want to:
$('#micropost').replaceWith("<%= escape_javascript render(:file => 'micropost_form.html.erb') %>");
Or, you could use the jquery append instead of replaceWith.