Is it possible to call a javascript function from a controller in rails?
To include a JavaScript function, it is as simple as include a <script> tag and define the function inside the script block. Now, to call the function, add an onclick event on the employee name hyperlink and call the function.
You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.
What I do is to make a Rails controller produce a javascript action. Is have it call a partial that has javascript included in it.
Unless you want that activated on page load, I would set it up via AJAX. So that I make an AJAX call to the controller which then calls a javascript file.
This can be seen via voting :
First the AJAX
//This instantiates a function you may use several times.
jQuery.fn.submitWithAjax = function() {
this.live("click", function() {
$.ajax({type: "GET", url: $(this).attr("href"), dataType: "script"});
return false;
});
};
// Here's an example of the class that will be 'clicked'
$(".vote").submitWithAjax();
Second the Controller
The class $(".vote")
that was clicked had an attribute href that called to my controller.
def vote_up
respond_to do |format|
# The action 'vote' is called here.
format.js { render :action => "vote", :layout => false }
end
end
Now the controller loads an AJAX file
// this file is called vote.js.haml
== $("#post_#{@post.id}").replaceWith("#{ escape_javascript(render :partial => 'main/post_view', :locals => {:post_view => @post}) }");
You have successfully called a javascript function from a controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With