Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling javascript functions from controller

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

like image 417
ssri Avatar asked Feb 16 '11 13:02

ssri


People also ask

How to call JavaScript function in MVC View?

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.

How Call JavaScript function from code behind in MVC?

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.


1 Answers

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.

like image 53
Trip Avatar answered Sep 24 '22 12:09

Trip