Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails prevent layout during AJAX request

I have searched around and have not been able to find a solution for this type of mechanic. I want to load all pages normally in Rails, but whenever I do an ajax request I just want to return the page without the layout. So anytime I make an ajax requst I can append a ?page=true or something along those lines and have Rails just return the page without the layout.

Is this possible? Is there a better way to do it that I am missing?

Thanks for any help!

Final Solution Working Code:

In the controller all you need to do is append a little logic to the format.html in the respond_to block.

In the show method for example

def show
    # code beforehand

    respond_to do |format|
        format.html { render :layout => !request.xhr? }
        # other formats
    end
end

And that's it! Prevent layouts during AJAX requests!

Note: Thanks to the smathy's comment on his answer this was simplified further. I originally had format.html { render :layout => nil if request.xhr? } This solution works just as well, but smathy's modification keeps it even simpler.

like image 635
KayoticSully Avatar asked Jul 02 '12 01:07

KayoticSully


1 Answers

You don't need to add that parameter, request.xhr? will return true in your controller when it's an Ajax request. Just use that to decide whether to render the layout or not.

like image 59
smathy Avatar answered Oct 14 '22 12:10

smathy