rj487
rj487

Reputation: 4634

How to pass javascript variable to rails partial view

I got a situation, there is a Javascript variable I need pass to rails partial view.

For example in test.html.erb

<script type="text/javascript">
var array  =  <%= raw sort_section %>
    for(i = 0; i < array.length; i++) {
        $('#test').append("<%= j render :partial => 'section_in_panel', :locals => {:section => raw array[i]} %>");
    }
</script>

But it keep throwing syntax error, I have try many ways like

{:section => j sort_section_js[i]} %>"
{:section =>" + sort_section_js[i] + "}%>"

I need to use that because I want to call ajax to change array dynamically.

Update

So, maybe I need to write a controller

def get_new_variable
    ...
    return new_variable
end 

Then in the test.html.erb

<script>
$('test').onclick(function(event) {
   //write some ajax call
   //get new_variable
   $('#test').empty();
   $('#test').append("<%= j render :partial => 'section_in_panel', :locals => {:section => raw new_variable} %>");
  });
)</script>

Is that right direction?

Upvotes: 0

Views: 4473

Answers (2)

egoholic
egoholic

Reputation: 317

You can use gem gon or simply do something like this:

<script>
  MyVars[:someVar] = <%= some_value %>;
</script>

But, I recommend you to separate your backend an frontend code and use JSON for passing data to JS.

Upvotes: 0

XavM
XavM

Reputation: 873

As Alberto Juan wrote in comment, you can't use javascript variable in ruby code. Ruby code will be interpreted before javascript and will not know what is the i.

Update: Your update will not work either as your using new_variable you get in your javascript code.

For using partial after ajax call, follow instructions in this link

Example:

items/index.html.erb

<div class="grid">
  <% @categories.each do |cat| %>
    <%= link_to cat.name, fetch_items_path(:cat_id => cat.id), :remote => true %>
  <% end %>

  <%= render partial: 'item_grid', locals: { items: @items} %>
</div>

routes.rb

get "/fetch_items" => 'items#from_category', as: 'fetch_items'

items_controller.rb

def index
    @items = Item.all
    @categories = Category.all
end

def from_category
    @selected = Item.where(:category_id => params[:cat_id])
    respond_to do |format|
        format.js
    end
end

views/items/from_category.js.erb

$("#items_grid").html("<%= escape_javascript(render partial: 'items_list', locals: { items: @selected } ) %>");  

Upvotes: 1

Related Questions