0

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??

4
  • how come you're getting the data as json? I'm not sure it matters but my first blush would have been to interpolate the straight value into the string you're building there...and where is asset_org defined? Commented Jul 13, 2011 at 19:18
  • so shoud I do convert it to string like <%= submit_tag "Create Slideshow",:Onclick=>{"insert_slide('#{params[:ed]}', '#{asset_org['height'].to_s}', '#{asset_org['width'].to_s}')"} %> Commented Jul 13, 2011 at 19:42
  • I am new to ruby on rails... So its a learning stage for me;) Commented Jul 13, 2011 at 19:48
  • Yeah, give that a try and let me know...and I don't think you need the single quotes around the javascript parameters...those are numbers, right? The basic rule of thumb here is that what you put in the :onclick value is going to be the string that the template puts down verbatim... Commented Jul 14, 2011 at 11:37

1 Answer 1

2

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)"
Sign up to request clarification or add additional context in comments.

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.