Tom Cartwright
Tom Cartwright

Reputation: 11

Render a partial in rails using jquery

I am trying to setup a navigation bar on my home page that loads a partial into a div element when the user clicks on the links. I have followed the steps in this post and modified them as I thought I needed: Rails 3 - link_to to call partial using jquery ajax

My code:

views/pages/home.html.erb:

<%= link_to "Files", :action => 'load_upload_partial', :remote => true %>

. . .

<div id="main_frame"></div>

pages_controller:

def load_upload_partial  
    respond_to do | format |  
      format.js {render :layout => false}  
    end
end

/views/uploads/load_upload_partial.js.erb:

$("#main_frame").html( "<%= escape_javascript( render( :partial => "/upload/upload_form" ) %>" );

The partial in this example is just a form. When I click on the link I get a blank page with this is the address bar: http://localhost:3000/load_upload_partial?remote=true

This makes me think that link is not triggering an ajax GET request (if that's the correct terminology). If that is the case is there anything I need to be adding to my application.js file? I followed the railscast #136 on rails and jquery but couldn't figure out which bits of the application.js code applied to my case. Any thoughts are much appreciated. Thanks. Tom

Upvotes: 1

Views: 4697

Answers (4)

Pat McGee
Pat McGee

Reputation: 379

ran into this same problem - the hint was in the malformed html produced - take a look at the value of the href attribute of the tag produced by your code. I bet it looks funky. Here's the correct code:

    <%= link_to "Files", your_path, action: 'load_upload_partial', remote: true %>

Upvotes: 0

Nick Res
Nick Res

Reputation: 2244

have you tried using .load() instead of .html()?

Also, try using this line instead:

$("#main_frame").html( "<%= escape_javascript( render( :partial => '/upload/upload_form' ) %>" );

Upvotes: -1

lucapette
lucapette

Reputation: 20724

I think you have to change your link_to to:

<%= link_to "Files", {:action => 'load_upload_partial' }, remote => true %>

The problem is related to the method signature of link_to.

Upvotes: 0

apneadiving
apneadiving

Reputation: 115541

I now tend to avoid using RJS like you're intending to. I prefer creating js templates with tools like handlebars.

I only use ajax to get raw data and then recreate the partial client side. It's much better for server load and data transfer.

Upvotes: 4

Related Questions