Passing Rails variable to JavaScript -
i want pass variable rails controller javascript file. found solutions , have:
# controller def index @coords = map.all end #view <%= content_tag 'div', id: 'coords', data: {coords: @coords } %> <% end %> #javascript alert($('#coords').data(coords)); edit:
$('#coords').data(coords) returns object object.
how access particular attribute of coords such coord.lat etc. in javascript? also, @coords converted json automatically?
note: couldn't use gon gem. think not supported in rails 4.2. need solution without gems.
when retrieving data attribute values jquery .data(key), key use should string. , yeah data: { coords: @coords} converts @coords json string automatically. think should work if call :
$('#coords').data('coords'); # returns array of javascript coord objects. $('#coords').data('coords')[0].id; # returns first coord's id.
Comments
Post a Comment