Javascript Response from Rails Controller leads to Uncaught SyntaxError: Unexpected token :












1















I have a form that creates a relation and when the form is submitted, javascript code that addes the newly connected nodes and the relations connecting them to the cytoscape graph should be returned:



The form:



<%= form_for Relation.new, :url => url_for(:controller => 'relations', :action => 'add_dependency'), remote: true do |f| %>
<%= f.hidden_field :to_id, :value => @article.id %>
<%= f.hidden_field :graph, :value => 1 %>
<%= f.select :from_id, , {}, {class: "select-article"} %>
<%= f.submit "Add a dependency of this article." %>
<% end %>


The controller code:



  def add_dependency
@relation = Relation.find_or_create_by(relation_params)
@relation.user << current_user

respond_to do |format|
if @relation.save
elements = json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3))
format.json { render :show, status: :created, location: @relation }
format.js { render js: "ancestors.add( #{elements} ); console.log('Hello');" }
else
format.json { render json: @relation.errors, status: :unprocessable_entity }
end
end
end


I get this error (and no "Hello") in the javascript console:



Uncaught SyntaxError: Unexpected token :
at processResponse (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:244)
at rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:173
at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:228)


This is the response:



ancestors.add( {:edges=>, :nodes=>[{:data=>{:id=>200, :title=>"Test Yourself: Area & arc length using calculus", :href=>"http://localhost:3000/articles/200", :rank=>0.000459770114943, :color=>"grey"}}]} ); console.log('Hello');









share|improve this question

























  • What was the rendered response there? (you can find out in browser's network tab)

    – Sergio Tulentsev
    Nov 25 '18 at 16:46













  • Do you have to wrap it in script tags maybe?

    – unflores
    Nov 25 '18 at 16:55













  • @SergioTulentsev I added it to the question.

    – troricleba
    Nov 25 '18 at 16:56











  • @unflores No, this worked with a simpler script (that just reloaded the site) without a script tag.

    – troricleba
    Nov 25 '18 at 16:57
















1















I have a form that creates a relation and when the form is submitted, javascript code that addes the newly connected nodes and the relations connecting them to the cytoscape graph should be returned:



The form:



<%= form_for Relation.new, :url => url_for(:controller => 'relations', :action => 'add_dependency'), remote: true do |f| %>
<%= f.hidden_field :to_id, :value => @article.id %>
<%= f.hidden_field :graph, :value => 1 %>
<%= f.select :from_id, , {}, {class: "select-article"} %>
<%= f.submit "Add a dependency of this article." %>
<% end %>


The controller code:



  def add_dependency
@relation = Relation.find_or_create_by(relation_params)
@relation.user << current_user

respond_to do |format|
if @relation.save
elements = json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3))
format.json { render :show, status: :created, location: @relation }
format.js { render js: "ancestors.add( #{elements} ); console.log('Hello');" }
else
format.json { render json: @relation.errors, status: :unprocessable_entity }
end
end
end


I get this error (and no "Hello") in the javascript console:



Uncaught SyntaxError: Unexpected token :
at processResponse (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:244)
at rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:173
at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:228)


This is the response:



ancestors.add( {:edges=>, :nodes=>[{:data=>{:id=>200, :title=>"Test Yourself: Area & arc length using calculus", :href=>"http://localhost:3000/articles/200", :rank=>0.000459770114943, :color=>"grey"}}]} ); console.log('Hello');









share|improve this question

























  • What was the rendered response there? (you can find out in browser's network tab)

    – Sergio Tulentsev
    Nov 25 '18 at 16:46













  • Do you have to wrap it in script tags maybe?

    – unflores
    Nov 25 '18 at 16:55













  • @SergioTulentsev I added it to the question.

    – troricleba
    Nov 25 '18 at 16:56











  • @unflores No, this worked with a simpler script (that just reloaded the site) without a script tag.

    – troricleba
    Nov 25 '18 at 16:57














1












1








1








I have a form that creates a relation and when the form is submitted, javascript code that addes the newly connected nodes and the relations connecting them to the cytoscape graph should be returned:



The form:



<%= form_for Relation.new, :url => url_for(:controller => 'relations', :action => 'add_dependency'), remote: true do |f| %>
<%= f.hidden_field :to_id, :value => @article.id %>
<%= f.hidden_field :graph, :value => 1 %>
<%= f.select :from_id, , {}, {class: "select-article"} %>
<%= f.submit "Add a dependency of this article." %>
<% end %>


The controller code:



  def add_dependency
@relation = Relation.find_or_create_by(relation_params)
@relation.user << current_user

respond_to do |format|
if @relation.save
elements = json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3))
format.json { render :show, status: :created, location: @relation }
format.js { render js: "ancestors.add( #{elements} ); console.log('Hello');" }
else
format.json { render json: @relation.errors, status: :unprocessable_entity }
end
end
end


I get this error (and no "Hello") in the javascript console:



Uncaught SyntaxError: Unexpected token :
at processResponse (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:244)
at rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:173
at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:228)


This is the response:



ancestors.add( {:edges=>, :nodes=>[{:data=>{:id=>200, :title=>"Test Yourself: Area & arc length using calculus", :href=>"http://localhost:3000/articles/200", :rank=>0.000459770114943, :color=>"grey"}}]} ); console.log('Hello');









share|improve this question
















I have a form that creates a relation and when the form is submitted, javascript code that addes the newly connected nodes and the relations connecting them to the cytoscape graph should be returned:



The form:



<%= form_for Relation.new, :url => url_for(:controller => 'relations', :action => 'add_dependency'), remote: true do |f| %>
<%= f.hidden_field :to_id, :value => @article.id %>
<%= f.hidden_field :graph, :value => 1 %>
<%= f.select :from_id, , {}, {class: "select-article"} %>
<%= f.submit "Add a dependency of this article." %>
<% end %>


The controller code:



  def add_dependency
@relation = Relation.find_or_create_by(relation_params)
@relation.user << current_user

respond_to do |format|
if @relation.save
elements = json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3))
format.json { render :show, status: :created, location: @relation }
format.js { render js: "ancestors.add( #{elements} ); console.log('Hello');" }
else
format.json { render json: @relation.errors, status: :unprocessable_entity }
end
end
end


I get this error (and no "Hello") in the javascript console:



Uncaught SyntaxError: Unexpected token :
at processResponse (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:244)
at rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:173
at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:228)


This is the response:



ancestors.add( {:edges=>, :nodes=>[{:data=>{:id=>200, :title=>"Test Yourself: Area & arc length using calculus", :href=>"http://localhost:3000/articles/200", :rank=>0.000459770114943, :color=>"grey"}}]} ); console.log('Hello');






javascript ruby-on-rails cytoscape.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 17:08







troricleba

















asked Nov 25 '18 at 16:28









troriclebatroricleba

488




488













  • What was the rendered response there? (you can find out in browser's network tab)

    – Sergio Tulentsev
    Nov 25 '18 at 16:46













  • Do you have to wrap it in script tags maybe?

    – unflores
    Nov 25 '18 at 16:55













  • @SergioTulentsev I added it to the question.

    – troricleba
    Nov 25 '18 at 16:56











  • @unflores No, this worked with a simpler script (that just reloaded the site) without a script tag.

    – troricleba
    Nov 25 '18 at 16:57



















  • What was the rendered response there? (you can find out in browser's network tab)

    – Sergio Tulentsev
    Nov 25 '18 at 16:46













  • Do you have to wrap it in script tags maybe?

    – unflores
    Nov 25 '18 at 16:55













  • @SergioTulentsev I added it to the question.

    – troricleba
    Nov 25 '18 at 16:56











  • @unflores No, this worked with a simpler script (that just reloaded the site) without a script tag.

    – troricleba
    Nov 25 '18 at 16:57

















What was the rendered response there? (you can find out in browser's network tab)

– Sergio Tulentsev
Nov 25 '18 at 16:46







What was the rendered response there? (you can find out in browser's network tab)

– Sergio Tulentsev
Nov 25 '18 at 16:46















Do you have to wrap it in script tags maybe?

– unflores
Nov 25 '18 at 16:55







Do you have to wrap it in script tags maybe?

– unflores
Nov 25 '18 at 16:55















@SergioTulentsev I added it to the question.

– troricleba
Nov 25 '18 at 16:56





@SergioTulentsev I added it to the question.

– troricleba
Nov 25 '18 at 16:56













@unflores No, this worked with a simpler script (that just reloaded the site) without a script tag.

– troricleba
Nov 25 '18 at 16:57





@unflores No, this worked with a simpler script (that just reloaded the site) without a script tag.

– troricleba
Nov 25 '18 at 16:57












2 Answers
2






active

oldest

votes


















1














I solved the problem by adding to_json:



json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3)).to_json





share|improve this answer































    0














    That response is not valid javascript and the reason is pretty simple. When you cast a Ruby hash to a string the result is not valid JS:



    irb(main):001:0> { :foo => 'bar'}.to_s
    => "{:foo=>"bar"}"


    Instead you need to encode it as JSON.



    irb(main):003:0> { :foo => 'bar'}.to_json
    => "{"foo":"bar"}"


    Due to quoting issues is easier done if you actually create a view instead of rendering inline:



    ancestors.add( <%= elements.to_json %> ); 
    console.log('Hello');





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53469521%2fjavascript-response-from-rails-controller-leads-to-uncaught-syntaxerror-unexpec%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      I solved the problem by adding to_json:



      json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3)).to_json





      share|improve this answer




























        1














        I solved the problem by adding to_json:



        json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3)).to_json





        share|improve this answer


























          1












          1








          1







          I solved the problem by adding to_json:



          json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3)).to_json





          share|improve this answer













          I solved the problem by adding to_json:



          json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3)).to_json






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 25 '18 at 18:00









          troriclebatroricleba

          488




          488

























              0














              That response is not valid javascript and the reason is pretty simple. When you cast a Ruby hash to a string the result is not valid JS:



              irb(main):001:0> { :foo => 'bar'}.to_s
              => "{:foo=>"bar"}"


              Instead you need to encode it as JSON.



              irb(main):003:0> { :foo => 'bar'}.to_json
              => "{"foo":"bar"}"


              Due to quoting issues is easier done if you actually create a view instead of rendering inline:



              ancestors.add( <%= elements.to_json %> ); 
              console.log('Hello');





              share|improve this answer




























                0














                That response is not valid javascript and the reason is pretty simple. When you cast a Ruby hash to a string the result is not valid JS:



                irb(main):001:0> { :foo => 'bar'}.to_s
                => "{:foo=>"bar"}"


                Instead you need to encode it as JSON.



                irb(main):003:0> { :foo => 'bar'}.to_json
                => "{"foo":"bar"}"


                Due to quoting issues is easier done if you actually create a view instead of rendering inline:



                ancestors.add( <%= elements.to_json %> ); 
                console.log('Hello');





                share|improve this answer


























                  0












                  0








                  0







                  That response is not valid javascript and the reason is pretty simple. When you cast a Ruby hash to a string the result is not valid JS:



                  irb(main):001:0> { :foo => 'bar'}.to_s
                  => "{:foo=>"bar"}"


                  Instead you need to encode it as JSON.



                  irb(main):003:0> { :foo => 'bar'}.to_json
                  => "{"foo":"bar"}"


                  Due to quoting issues is easier done if you actually create a view instead of rendering inline:



                  ancestors.add( <%= elements.to_json %> ); 
                  console.log('Hello');





                  share|improve this answer













                  That response is not valid javascript and the reason is pretty simple. When you cast a Ruby hash to a string the result is not valid JS:



                  irb(main):001:0> { :foo => 'bar'}.to_s
                  => "{:foo=>"bar"}"


                  Instead you need to encode it as JSON.



                  irb(main):003:0> { :foo => 'bar'}.to_json
                  => "{"foo":"bar"}"


                  Due to quoting issues is easier done if you actually create a view instead of rendering inline:



                  ancestors.add( <%= elements.to_json %> ); 
                  console.log('Hello');






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 25 '18 at 18:05









                  maxmax

                  46.4k1060105




                  46.4k1060105






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53469521%2fjavascript-response-from-rails-controller-leads-to-uncaught-syntaxerror-unexpec%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Create new schema in PostgreSQL using DBeaver

                      Deepest pit of an array with Javascript: test on Codility

                      Costa Masnaga