Pass JavaScript variables to Rails controller 1

Posted by jay Mon, 13 Apr 2009 23:26:00 GMT

Google query doesn’t give much useful result on this topic. What we discuss here is if there is a value/function getParameters() in JavaScript returns "message = hello_world" (a URL query). How do you pass the JS variable into controller?

link_to_remote

Most common way is using link_to_remote which constructs an Ajax call, but the drawback is you have to handle the params[:message] using RJS template (or please let me know if I was wrong). Here is the example:

<%= link_to_remote "Create Post", :url => {:controller=>'posts', :action =>'new'},  :method => :post, :with =>"getParameters();" %>

As you see, the :with option will eventually become :with => "message=hello_world". A new parameter is accessible by calling params[:message]. But what if I only want to render another page?

capture block

Capture block captures a variable for the view which can be reused. The idea is to call the JavaScript inside capture block to pass it as a Rails variable in view. The @param variable is readable in the view.

<% @param = capture do %>
<%= javascript_tag "document.write(getParameter());" %>
<% end %>

link_to_function

Remember that we have already passed the JavaScript value to @param variable, it is used here. An inline redirect_to does the trick, that redirects to the new action and value is accessible by calling params[:message].

<%= link_to_function "Create Post" do |page|
  	page.redirect_to  "/posts/new" + "?" + @param
  end %>

I’m sure that you will have other ways of using these tricks in difference situation, but hope you get the idea and use them whenever is suitable.

Comments

Leave a comment

  1. Stephan 10 months later:

    I might just be being dumb here, but the capture block captures all of the HTML, not just the result of the getParameters() call. So when I try the above, I get a request which has:

    Parameters: {“//”=>{“>”=>nil}, ”

    as parameters.

    Am I being dumb?

Comments