David David - 3 months ago 13
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>
</div>
<div>
<button type="button" class="btn btn-primary"id="btn_next">Next</button>
</div>


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

$(document).ready(function(){
$("#btn_next").click(function(){
$.ajax({
type:'POST',
url:'/study',
data: { id: "demo.html" },
success:function(result){
$("#lesson").html(result);
}
});
});


});

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
end


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>
</table>


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!

Answer

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
Comments