1

I want to pass a variable from a Rails controller to a JavaScript file. I found some solutions and now I have:

# controller 
def index
    @coords = Map.all
end


#view 
<%= content_tag 'div', id: 'coords', data: {coords: @coords } do %>
<% end %>
  
#javascript
 alert($('#coords').data(coords));

EDIT:

$('#coords').data(coords) returns an object Object.

How do I access a particular attribute of coords such as coord.lat etc. in javascript? Also, do @coords get converted to JSON automatically?

NOTE: I couldn't use gon gem. I think it is not supported in rails 4.2. So I need a solution without gems.

3
  • gon is working with rails 4.2. I have used it in one of my rails-4.2.1 projects Commented Jun 13, 2015 at 11:19
  • @MihailDavydenkov, can you show me the way you used it? Coz i couldn't Commented Jun 13, 2015 at 11:25
  • @MihailDavydenkov, github.com/gazay/gon/issues/90 Commented Jun 13, 2015 at 11:30

4 Answers 4

2

Here how I use gem gon with rails-4.2.0. Nothing special really:

# Gemfile.lock where rails binded to version 4.2.0
gon (5.2.3)
  actionpack (>= 2.3.0)
  json
  multi_json
  request_store (>= 1.0.5)
....
PATH
remote: engines/mobile_api
specs:
  mobile_api (0.1)
    itunes-receipt
    rails (~> 4.2.0)

# Gemfile
source 'http://rubygems.org'

gem 'rails', '4.2.0'
gem 'gon'

# layout main.html.slim
doctype html
html
  head
    meta charset="utf-8"
    = include_gon

# main_controller.rb (In the controller)
class MainController < ApplicationBaseController
  before_action :start_marketing_split_test
  layout 'main'

  # ... actions here

  def start_marketing_split_test
    split_test_name = 'ab_test_1'
    alternatives_loader =       
      Marketing::AB::AlternativesLoader.new(split_test_name)

    alternative = ab_test(split_test_name,        
                          alternatives_loader.alternatives)

    gon.push({"#{split_test_name}" => JSON.parse(alternative)})
 end

============================

But if you need solution without gon you can pass variables right in you backend templates:

For example:

# layouts/application.html.slim

doctype html
html
  head
    meta charset="utf-8"
    title
  body
javascript:
  window.app_options = {
    'flash_alert': "#{raw(flash[:alert])}",
    'flash_warning': "#{raw(flash[:warning])}",
    'flash_notice': "#{raw(flash[:notice])}",
    'current_user_id': "#{current_user.try(:id)}",
    'current_user_phone': "#{current_user.try(:phone)}"
  };
Sign up to request clarification or add additional context in comments.

Comments

1

When retrieving data attribute values with jQuery .data(key), the key you use should be a String. And yeah data: { coords: @coords} converts @coords to JSON string automatically. So I think it should work for you if you call it like this :

$('#coords').data('coords');
# Returns array of JavaScript coord objects.
$('#coords').data('coords')[0].id;
# Returns first coord's id.

7 Comments

Uncaught TypeError: Cannot read property '0' of undefined. I also think that this should work. Have no idea why it isn't
Okay. Btw, what do you see for the data attribute in that div, in resulted HTML ?
<div id="coords" data-coords="[{'id':1,'vibration_level':456,'lat':'71.45543','lon':'53.43424','time_sent':'1994-05-20T00:00:00.000Z','created_at':'2015-06-13T06:53:30.789Z','updated_at':'2015-06-13T06:53:30.789Z'}, </div> etc . I deleted some part of it to make it shorter.
There isn't any problem with the generated data attribute. I'm sure there might be something wrong in the way you're retrieving it. Can you try to retrieve it in your browser's console ?
Try the first line first, see what's coming.
|
0

what about using a helper method like following

<%= content_tag 'div', id: 'coords', data: <%= json_for @coords%> do %> module ApplicationHelper def json_for(target_model) target_model.to_json #generates a json object end end

https://github.com/rails-api/active_model_serializers

1 Comment

ok, your solution helped to generate json. But I still have problems accesing it in my javascript file.
-1

You can use in view file

<%= javascript_tag do %>
  var1 = @coords.lat
  var2 = @coords.lgt
<% end %>

then you can access var1 and var2 through javascript code.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.