Reputation: 35
I need some help with my response from AJAX call. Here is what I want to do:
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!
Upvotes: 3
Views: 7631
Reputation: 18018
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
Upvotes: 9