0

I have h variable in my view , h variable:

[{"folder"=>"High Risk", "weight"=>"38.8", "stocks"=>[{"id"=>"id3", "name"=>"Indian Oil Corporation Ltd.", "weight"=>"14.4"}, {"id"=>"id5", "name"=>"Atul Auto Ltd.", "weight"=>"13.7"}, {"id"=>"id6", "name"=>"Hindustan Zinc Ltd.", "weight"=>"10.6"}]}, {"folder"=>"Expecting PE ratio", "weight"=>"42.3", "stocks"=>[{"id"=>"id7", "name"=>"Infosys Ltd.", "weight"=>"42.3"}]}, {"folder"=>"from kite", "weight"=>"12.8", "stocks"=>[{"id"=>"id8", "name"=>"Hindustan Unilever Ltd.", "weight"=>"12.8"}]}, {"folder"=>"Low Margin", "weight"=>"6.1", "stocks"=>[{"id"=>"id9", "name"=>"Jindal Steel & Power Ltd.", "weight"=>"6.1"}]}]

This is my script inside view.erb

<script>
if (top.location != location) {
       top.location.href = document.location.href ;
    }
///Some function giving 'val' value

    jQuery.ajax({
     data: 'val=' + total_span,
     dataType: 'script',
     type: 'post',
     url: "/portfolio/slide_change"
     });

    </script>

I have two doubt i have:

1)How and where i should declare new variable in javascript to get h value from ruby code in this file?(way to pass h from ruby to javascript)

2)I wanted to post this variable also to the backhand with 'val' how i can do that? Is it possible to post two variable at a time or do i need to concatenate h with 'val'?

Deepender Singla
  • 999
  • 9
  • 28

1 Answers1

2

you can use ruby variables in ERB. assuming you have variable @stocks available in your erb, you can output its JSON representation using <%= @stocks.to_json %>. so in your view.erb you can write:

<script>
if (top.location != location) {
       top.location.href = document.location.href ;
    }


    var val = <%= h.to_json %>; //rendered view will have actual array there.

    jQuery.ajax({
     data: 'val=' + total_span,
     dataType: 'script',
     type: 'post',
     url: "/portfolio/slide_change"
     });

    </script>
Iuri G.
  • 10,460
  • 4
  • 22
  • 39