0

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.

Community
  • 1
  • 1
user3266824
  • 1,233
  • 2
  • 14
  • 27

1 Answers1

0

What you are doing now is:

require 'json'

JSON.parse('data') # which throws unexpected token at 'data' because JSON can't parse the string 'data'

If your goal is simply to append the parsed json to a dom element then i don't see the need to require JSON and do it in ruby?

This javascript should do fine (check this SO answer):

.done(function(data) {
  $("#user_data").append(JSON.parse(data));
}
Community
  • 1
  • 1
Nimir
  • 5,727
  • 1
  • 26
  • 34
  • I need it in ruby because I would like to add ruby's link_to method to pass information Im getting from the json object back to the controller when clicked. – user3266824 Sep 23 '14 at 12:16