views:

325

answers:

2

Hi guys,

I'm trying to make an AJAX enabled web page using rails and jQuery. The problem that I am running into is that when I try and load a view into a div using jQuery's AJAX method I am getting my application layout returned with the view. Is there a way to only retrieve the view data if it's an AJAX request, but load my application layout as well if its not an AJAX request?

Here's the controllers method that I am calling:

def new
   @blog = Blog.new

   respond_to do |format|
       format.html # Goes to the new.html.erb view.
       format.xml { render :xml => @blog }
   end
end

Thanks for the help.

+4  A: 

Add this line to your respond_to block:

format.js { render :layout => false }

This says that for javascript requests, don't render the layout. Now it should work for both ajax requests, and regular web links.

Jaime Bellmyer
+3  A: 

You have to add the js format to your respond_to block:

format.js do
  render :update do |page|
    page.replace_html "id_of_your_div" :partial => "something"
  end
end

or

format.js do
  render :js => "$('#id_of_your_div').html('#{escape_javascript(render_to_string(:partial => 'something')}');"
end

Or even you could put the javascript code in a file called new.js.erb without the need of the format.js block.

I recommend you to read the rails guides: http://guides.rubyonrails.org/layouts_and_rendering.html#using-render-with-update