rubyist
rubyist

Reputation: 3132

passing ruby arrays to javascript function from view page

How do I pass the ruby arrays to Js func and access it(from JS func)from a view page.. In my view page I have defined an array as

<% asset_org.push({'url' => image_data['url'],
'height' => height_org,
'width'=> width_org                              
 }) %>

And I have passed this array as

<%= submit_tag "Create Slideshow",:Onclick=>"insert_slide(#{asset_org['height'].to_json}, #{asset_org['width'].to_json)" %>

But in the JS function(defined as function insert_slide(height, width)) of insert_slide I am not able to access this array of height and width

It is showing an error as asset_org is not defined... Any inputs on this??

Upvotes: 0

Views: 993

Answers (1)

simianarmy
simianarmy

Reputation: 1507

Array's to_json() is a good way to pass the data if you can guarantee that the array doesn't contain any values that will cause to_json to raise exceptions.

Other than some scope issues you might be having (try using <%= debug asset_org %> in your view), you aren't accessing the array values properly in your submit_tag code.

Assuming your array only has one item, it should look like:

<%= submit_tag "Create Slideshow",
  :onclick=>"insert_slide('#{asset_org[0]['height']}', '#{asset_org[0]['width']}')" 
%>

Even better, modify insert_slide() to take an object parameter, then you could call it like this:

:onclick=>"insert_slide(#{asset_org[0]}.to_json)"

Upvotes: 2

Related Questions