absessive
absessive

Reputation: 1171

How to pass a variable from controller to javascript within a view?

I have an array @fields which has text and an id, asset_id. To pass local variables from controller to view in render we use

render(:template => "assets/invalid", :locals => {:asset_id => params[:id], :fields => @fields})

The view is

<div id="panel">
  <script>
    alert('Invalid values for ')
    window.location = "../assets/" 
  </script>
</div>

This should generate a popup box. However, I want the popup box to redirect to "../assets/asset_id" and also display 'Invalid values for + fields'

The following doesn't work,

<div id="panel">
  <script>
    var fields = fields
    var asset_id = asset_id 
    alert('Invalid values for ' + fields )
    window.location = "../assets/" + asset_id 
  </script>
</div>

Upvotes: 0

Views: 1020

Answers (3)

Derrick W
Derrick W

Reputation: 332

An approach I have used in a couple apps where it's necessary for the client code to use server data is to build a hash and render it into a json literal on the page and have all my JS reference that object. It's the same approach as mentioned above but it's a bit cleaner because you don't have to mix a lot of server tags into your JS code. Easier to read and maintain.

Upvotes: 1

Victor Moroz
Victor Moroz

Reputation: 9225

Could it be as simple as this?

<div id="panel">
  <script>
    var fields = <%= fields.to_json %>
    var asset_id = <%= asset_id.to_json %>
    alert('Invalid values for ' + fields )
    window.location = "../assets/" + asset_id 
  </script>
</div>

UPDATE And by the way, why do you need to pass fields or params as a local variable, why not to use @fields in your view?

Upvotes: 3

Viren
Viren

Reputation: 5962

What wrong with this

<div id="panel">
  <script>
    var fields = fields
    var asset_id = <%= asset_id %> 
    alert('Invalid values for ' + fields )
    window.location = "../assets/" + asset_id 
  </script>
</div>

Now you can pass data to html for advance thing you can use something like gon check out gon gem it might help

Upvotes: 0

Related Questions