Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails: Send JSON data from server to client asynchronously
    primarykey
    data
    text
    <p><strong>Background and my research</strong></p> <p>I would like to send data from server to client without reloading the page on the browser. I was reading <a href="http://guides.rubyonrails.org/layouts_and_rendering.html" rel="nofollow">Rails guide</a> and using JSON seemed promising. (Correct me if I am wrong).</p> <blockquote> <p>2.2.8 Rendering JSON</p> <p>JSON is a JavaScript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:</p> <p>render :json => @product You don’t need to call to_json on the object that you want to render. If you use the :json option, render will automatically call to_json for you.</p> </blockquote> <hr> <p><strong>Problem</strong></p> <p>I want to be able to render this JSON object back in the browser side. The following are appropriate code for the problem.</p> <p><strong>VideosController</strong></p> <pre><code>class VideosController &lt; ApplicationController include VideosHelper def home @video = Video.last end def next @next_video = next_video(params[:id]) render :json =&gt; @next_video end end </code></pre> <p><strong>next.json.erb</strong></p> <pre><code>{ "title": "&lt;%= @video.title %&gt;" "url": "&lt;%= @video.url %&gt;" "youtube_id": "&lt;%= @video.youtube_id %&gt;" "genre": "&lt;%= @video.genre %&gt;" "category": "&lt;%= @video.category %&gt;" "likes": "&lt;%= @video.likes %&gt;" "dislikes": "&lt;%= @video.dislikes %&gt;" "views": "&lt;%= @video.views %&gt;" "user_id": "&lt;%= @video.user_id %&gt;" "created_at": "&lt;%= @video.created_at %&gt;" "updated_at": "&lt;%= @video.updated_at %&gt;" } </code></pre> <p>If I want to render <code>@next_video</code> JSON object on <code>home</code> action. How do I do this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload