0

When I click the submit button, I am rendering with json in controller.

My json is {notes: array[1], array[2]}. Now I am rendering view.html.erb file. I want to show the values in notes like <%= notes %> in this file, how to display it ?

code_aks
  • 1,972
  • 1
  • 12
  • 28
  • 1
    what about the loop through array . js file and add values in html.erb with .appendChild()? – bad_kotya Jul 01 '20 at 11:01
  • The json you are showing is invalid json syntax. Also note that the json is in javascript on the client side, and your controller is on the server side. As @bad_kotya points out, you don't need to send the data to the server side only to be rendered back to the client side. You can use javascript to render the data in the DOM directly. – lurker Jul 01 '20 at 11:35
  • Does this answer your question? [How to pass a javascript variable into a erb code in a js view?](https://stackoverflow.com/questions/4959770/how-to-pass-a-javascript-variable-into-a-erb-code-in-a-js-view) – bork Jul 01 '20 at 12:16

2 Answers2

2

If notes is an arary you can loop over it and display the content in your .erb.html file as below:

<div>
  <% notes.each_with_index do | note, index | %>
    <div id="title">
      <%= note[:title] %>
    </div>
  <% end %>
</div>
rishabh0211
  • 433
  • 4
  • 10
  • It is showing like this `undefined local variable or method notes` –  Jul 01 '20 at 10:28
  • @SNandy Does your `.html.erb` file has access to notes? – rishabh0211 Jul 01 '20 at 10:29
  • That's my question. How to pass json value `notes` to `html.erb` ? –  Jul 01 '20 at 10:31
  • The `notes` variable is in JS `(.js)` file or in ruby `(.rb)` file? If it is ruby file, you can proceed as @Viktor suggested, create an instance variable in your controller and use it in your view. – rishabh0211 Jul 01 '20 at 10:38
  • I gave in controller as `render json: { notes: @notes }` so in my js file, in success part, Iam getting the notes value. –  Jul 01 '20 at 10:44
0

sounds like you are confusing JSON requests with HTML request.

The incoming request should be a HTML

controller

# GET /the_controller/view
# not /the_controller/view.json <- wrong
def view
   @notes = array
end    

view.html.erb

<%= @notes %>

see @rishabh0211 answer for better presentation

if indeed you intend this to be a json request, through som ajax request or similiar, you need to specify that in your question.

oma
  • 38,642
  • 11
  • 71
  • 99