Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ajax request load view html only

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.

like image 519
Brian DiCasa Avatar asked Jan 17 '10 19:01

Brian DiCasa


Video Answer


2 Answers

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

like image 115
user252744 Avatar answered Nov 15 '22 06:11

user252744


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.

like image 41
Jaime Bellmyer Avatar answered Nov 15 '22 05:11

Jaime Bellmyer