1

I'm trying to make the "home" link in my <%= render 'layouts/header' %> do an ajax/jquery call to change the <%= yield %> in a partial inside my content div. all i get are blanks in the view.. <%= yield %> works fine when put in a partial without ajax, but it doesn't display anything when using ajax... can yield not be used this way?

all I'm really looking for is the ability to click on my sites navigation links without having to reload the entire page...

my application.html.erb file looks like so:

<head>
$(function() {
  $("#home").live("click", function() {
    $.get(this.href, null, null, "script");
  return false; }); });
</head>
<body>
  <div id="container">
    <%= render 'layouts/header' %>
    <div id="content">
      <%= render 'layouts/content' %>
    </div>
    <%= render 'layouts/footer' %>
  </div>
</body>

my <%= render 'layouts/header' %> contains:

<%= link_to "Home", root_path, :id => "home" %>

my <%= render 'layouts/content' %> only contains:

<%= yield %>

home.js.erb

$("#content").html("<%= escape_javascript(render("layouts/content")) %>");
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
thedeepfield
  • 6,138
  • 25
  • 72
  • 107

2 Answers2

2

Your usecase is exactly tackled by the rails-ajax gem.

All you have to do is configure it with div#content as its main default container, and your website will be automatically ajaxified using this container. No need to alter your application's code.

It handles a lot of hassle for you: bookmarking, history, scripts executions, redirections, forms, fallback for JS-disabled browsers...

You can also specify additional partials to be refreshed on some specific controllers' actions.

Muriel Salvan
  • 138
  • 1
  • 6
1

In home.js.erb you are rendering an empty layout file. Try rendering some view instead.

You can think of <%= yield %> as a placeholder for rendered view content in a layout file. If you render just the layout, there's nothing to be put in there.

http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield

Alternative solution

Add this to top of your controller to disable layouts for ajax requests:

layout Proc.new { |controller| controller.request.xhr? ? false : 'application' }

This will make all links inside of #header load with ajax and place the result to #content div:

$(function() {
    $('#header a').live('click', function() {
        $('#content').load(this.href);
        return false;
    });
});

Remove js format from your controller actions because that's not needed anymore.

Heikki
  • 15,329
  • 2
  • 54
  • 49
  • thanks for your response, I'm just starting to learn Jquery and just curious, if I wanted this to fade in where would I put .fadeIn()? – thedeepfield Jan 04 '11 at 03:18