Search code examples
javascriptruby-on-railsjsonjbuilder

No console output when using render and jbuilder


I'm running into this weird problem that causes the console to not show an output after parsing

 a= "<%=j render 'api/restaurants/index.json.jbuilder',restaurants: @restaurants %>";
json = $.parseJSON("<%= render 'api/restaurants/index.json.jbuilder',  restaurants: @restaurants %>");
 console.log(json);


a= "<%=j render 'api/restaurants/index.json.jbuilder', restaurants: @restaurants %>";
json = $.parseJSON("<%= render 'api/restaurants/index.json.jbuilder', restaurants: @restaurants %>");
console.log("console test");


a= "<%=j render 'api/restaurants/index.json.jbuilder', restaurants: @restaurants %>";
json = $.parseJSON("<%= render 'api/restaurants/index.json.jbuilder', restaurants: @restaurants %>");
console.log(a);

The code snippets above do not render anything in the console, however the code snippets below do give a console output.

a= "<%=j render 'api/restaurants/index.json.jbuilder', restaurants: @restaurants %>";
console.log(a);


 a= "<%=j render 'api/restaurants/index.json.jbuilder', restaurants: @restaurants %>";
 console.log("console test");

It seems like the parsing is stopping the console from outputting anything. Anyone have any ideas why this is happening and how to fix it


Solution

  • As reported in jQuery.parseJSON:

    Passing in a malformed JSON string results in a JavaScript exception being thrown.

    So, your api does not return a correct json.

    Example:

    $(function () {
      try {
        var a = $.parseJSON("{test: 1}");
        console.log(a);
      } catch(err) {
        console.log('Err: ' + err);
      }
    });
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>