Alexander Smith Alexander Smith - 6 months ago 8
Ruby Question

Using Rails Data for a Javascript function

How can I access the

@location.coordinates
data and use it in the
GetMarineWeather()
function for the query?

I want to be able to use the rails data and load the query coordinates.

How can I access the coordinates and fill the function when the page is loaded initially?

<p id="notice"><%= notice %></p>

<p><strong>Name:</strong><%= @location.name %></p>

<p><strong>Sub region:</strong><%= @location.sub_region %></p>

<p><strong>Region:</strong><%= @location.region %></p>

<p><strong>Coordinates:</strong><%= @location.coordinates %></p>

<div id="resultContainer"></div>


<!-- *********************************************************************** -->


<script type="text/javascript">

var resultContainer = $('#resultContainer');
var output = '';


$(document).ready(function () {
GetMarineWeather();
});


function GetMarineWeather(e) {
var marineWeatherInput = {
query: '26.16,-80.10',
format: 'JSON',
fx: '',
callback: 'MarineWeatherCallback'
};
JSONP_MarineWeather(marineWeatherInput);
e.preventDefault();
}


function MarineWeatherCallback(marineWeather) {

output = "<br/> Date: " + marineWeather.data.weather[0].date;
output += "<br/> Min Temp (f): " + marineWeather.data.weather[0].mintempF;
output += "<br/> Max Temp (f): " + marineWeather.data.weather[0].maxtempF;
output += "<br/> Cloud Cover: " + marineWeather.data.weather[0].hourly[0].cloudcover;

resultContainer.empty();
resultContainer.html(output);

}

</script>

Answer

It's common to set a data- attributes on a HTML tag to share server side information with JavaScript.

<div id="coordinates" data-coordinates="<%= @location.coordinates %>"></div>

After that you simply read it with JS:

$('#coordinates').data('coordinates')
Comments