5

Is it possible to call a javascript function from a controller in rails?

1
  • ssri, What I do is I call via AJAX to a Rails controller which then activates a partial that calls a javascript function. Commented Feb 16, 2011 at 14:38

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to call a function within vote.js.haml? How could you pass a variable when you make the function call?
Is this a rails method or a js method? You can pass variables to your .js file from your controller. So in my example's case, @post is described in the controller action for def vote as @post.. etc.
An important note for this setup is that the link_to function for ".vote" should have remote: true in order to have the js called rather than rendering a new page on click.
0

No, but you could output javascript that would be called immediately in your view e.g.

<script type="text/javascript">
   function IWillBeCalledImmediately()
   {
      alert('called');
   };
   IWillBeCalledImmediately();
</script>

However it would probably be better to use jquery and use the ready event.

<script type="text/javascript">
     $(function() { 
          alert('called');
      });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.