I am attempting to transfer JSON data from my database to the front-end in order to manipulate it using JavaScript. Initially, I created some temporary JSON data in my home.html.erb
file like this:
<%= javascript_tag do %>
window.testJSON_data =
[
{
"name" : "Bill Gates",
"telephone" : 123456789
},
{
"name" : "Elon Musk",
"telephone" : 987654321
}
];
console.log(testJSON_data); /* Works as expected - will print JSON data in console! */
<% end %>
The code above successfully displays the correct data and JSON format in the console log. However, when I attempt to use my actual database data with a similar approach, issues arise. After passing the data to my home controller and trying to capture it in home.html.erb
, the following Ruby code is executed:
class HomeController < ApplicationController
def index
@data = EmergencyFriend.all
@jsonData = JSON.pretty_generate(@data.as_json)
#render json: @jsonData
end
end
I have experimented with various methods but have not been able to output the data as an object. My attempts include:
console.log(JSON.stringify('<%= j @jsonData.as_json.html_safe %>'));
console.log(JSON.stringify('<%= j @jsonData.as_json %>'));
console.log(JSON.stringify('<%= j @jsonData %>'));
<%= javascript_tag do %>
console.log('<%= j @jsonData %>');
<% end %>
WILL RETURN:
[
{
"id": 1,
"first_name": "Emergency Contact",
...
"dial_code": 357
},
{
...
},
{
...
}
]
After spending quite some time troubleshooting, I'm still unable to identify where the issue lies. Whether it's incorrect data transfer or misprinting of the data remains unclear to me.
What steps should I take to effectively store JSON data from a Ruby controller to JavaScript?