Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to request an html page using an ajax request in Rails 3?

I'm trying to Rails to render the an .html.erb template through an ajax request under certain conditions. By default I keep getting back the .js.erb file when I send an ajax request.

I won't get into why I'm doing this, but I was wondering if there's either a way to specify when I'm sending the request through ajax that I'd like html content back rather than js, OR alternatively, if there's a way to refactor the following in Rails 3.1:

respond_to do |format|
  format.html
  format.js do
    if params[:page].nil?
      render "home.html.erb"
    else
      render "home.js.erb"
    end
  end
end

Thanks!

like image 752
Yuval Karmi Avatar asked Dec 12 '25 15:12

Yuval Karmi


1 Answers

Assuming you are using jquery, you can set the dataType option, ie

$.ajax('some/page', {dataType: 'html'})

Or

$.get('some/page', function(){ //callback}, 'html')

Adding the format to the URL (ie. request '/some/page.html') should also work (regardless of how you make your request)

like image 89
Frederick Cheung Avatar answered Dec 15 '25 07:12

Frederick Cheung