I am trying to parse a json string coming from my controller through an ajax call. The json string being parsed is in a js.erb file. I set my code up similar to this stack overflow suggestion: Parsing a JSON string in Ruby. I added the gem, However instead of simply adding the code I had to put <% %> around the ruby part of the code because it is a js.erb file and not an .rb file
my full js.erb file looks like this:
<% require 'json' %>
$(document).ready(function()
{
$('#collaboration_user_name').on('keyup', function() {
text = $(this).val();
// alert(text);
$.ajax({ url: "/collaborations?collaboration="+text,
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
}).done(function( data ) {
console.log( "data:", data );
users = JSON.parse(data);
$("#user_data ul li").remove();
$.each( users, function( index, value ) {
$("#user_data ul").append("<li role='presentation'>"+"<a role='menuitem' tabindex='-1' href='#'>"+users[index].name+ ", " +users[index].email+"</a>"+"</li>");
});
<% @user = "data" %>;
$("#user_data").append(<%= JSON.parse @user %>);
});
});
});
The code to note is the
<% require 'json' %>
at the top and the
<% @user = "data" %>;
$("#user_data").append(<%= JSON.parse @user %>);
at the bottom of the page. When I add these lines in I get an error.
JSON::ParserError in Wikis#edit
Showing /Users/warren/code/knowledgebank/app/views/layouts/application.html.erb where line #7 raised:
757: unexpected token at 'data'
(in /Users/warren/code/knowledgebank/app/assets/javascripts/collaborations.js.erb)
Extracted source (around line #7):
4<title>Knowledgebank</title>
5<%= stylesheet_link_tag "application", media: "all" %>
6
7<%= javascript_include_tag 'application'%>
8<%= csrf_meta_tags %>
9</head>
10<body>
How can I make JSON.parse for ruby to work? In javascript it is working fine.