6

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.

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This is the proper answer to the question AND to what I needed.
You are missing a coma before :partial in the first example
7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.