David David - 5 months ago 24
Ajax Question

Rails: Render HTML directly from controller.

I need some help with my response from AJAX call. Here is what I want to do:

  1. Make an AJAX call to my Rails app to get an HTML document.

  2. Inside the Rails controller, read the HTML document from disk. Then send the document to the view using "render html: @htmldoc"

  3. Inside the view, I have a tag ID "lesson" in a div. Using the response from the AJAX call that has the HTML document, I put the doc into the "lesson" tag. But the HTML is rendered as TEXTNODE with the "lesson" tag while I need it to be rendered as HTML.

Here is my view in new.html.erb:

<div id="lesson">
<h2>Choose a lesson on the left panel to start your study module.</h2>
<button type="button" class="btn btn-primary"id="btn_next">Next</button>

Here is my AJAX call in new.html.erb:

data: { id: "demo.html" },


Here is my routes.rb:

get '/study', to: 'study_sessions#new'
post '/study', to: 'study_sessions#create'

Here is my code inside the controller:

def create
@filename = params[:id]
@htmldoc = File.read("public/uploads/#{@filename}") if File.exist("public/uploads/#{@filename}")
render html: @htmldoc

Here is my demo.html file:

<table class="table table-striped">
<th>Head 1</th><th>Head 2</th>
<tr><td>Row 1</td><td>row 1</td></tr>
<tr><td>Row 2</td><td>row 2</td></tr>

Here is the result when I view from the browser before I clicked the button:

Choose a lesson on the left panel to start your study module.

Here is the result after I clicked the button:

<table class="table table-striped"> <th>Head 1</th><th>Head 2</th<tr><td>Row 1</td><td>row 1</td></tr> <tr><td>Row 2</td><td>row 2</td></tr> </table>

I would expect the demo.html file will be rendered as a nice HTML table, not a string of text.

Much appreciate for all the help folks!


You need to tell rails to render it as html content using .html_safe method. Try doing it like so:

render html: @htmldoc.html_safe