Jquery – Rendering Rails Partial from AJAX and passing in local variables from AJAX

ajaxjqueryruby-on-railsruby-on-rails-3

I'm trying to render a Rails partial with an AJAX request like in this link (and also pass in local variables to the rendered partial):

http://isotope11.com/blog/render-partials-with-ajax-requests

What he is doing is using .get to do an ajax call to a controller that renders a partial:

  $.get("/ean_hotels/"+ id, params, function(data){
  $('#hotelModalContent').html(data);
  }, "html");

  $('#hotelModal').reveal();

And the "render" at the end of his controller action in hotels_controller.rb:

render partial: 'hotel_modal_content', locals: { hotel: @hotel, hotel_review_widget: hotel_review_widget }, layout: false 

you can see that the controller code sets local variables for the partial to be rendered (i.e. hotel and hotel_review_widget).

I don't understand how to pass in these local variables from the original .get AJAX call.

I'm also not sure what params is for when doing the AJAX call with .get

I'd like to be able to pass in local variables from javascript through to the hotels_controller.rb which maps a local variable to a variable in the partial.

I appreciate any help here.

EDIT:

Adding partial code

_hotel_model_content.html.erb

<h3><%= hotel %></h3>

Best Answer

Client

According to the $.get and $.ajax docs, params will go into the query string part of the URL:

// request to /somethings?a=abc&b=2
$.get('/somethings', {a: 'abc', b: 2})

Server

Query string parameters can be accessed from Rails actions via a Hash-like object called params. [1]

class SomethingsController < ApplicationController
  def index
    puts params[:a] # if URL was /somethings?a=123, will print 123
  end
end

Putting it Together

Let's make a complete example with a partial.

Here is the client code:

// client call to /somethings?name=Something+123
$.get('/somethings', {name: 'Something 123'}, function(data){
  $('#target').html(data);
});

Here is the server:

class SomethingsController < ApplicationController
  def index
    # bind controller variable @name
    @name = params[:name]
  end
end

Inside the view app/views/somethings/index.html.erb:

<%= render :partial => 'some_partial', :locals => {:name => @name} %>

I've moved the partial rendering into a view. I think rendering partials from views is more standard than rendering partials directly from controllers.

Related Topic