0

I have a view with an ajax form:

<%= form_tag( {:action => 'some_action'}, {:remote => true}) do %>
...
  <%= submit_tag "Submit" %>
<% end %>

Now, in the target action, I want to display a partial

def some_action
  # some logic
  render :partial => "some_partial"
end

The partial is just html. _some_partial.html.erb could be

<br>Hi, this is the partial</br> 

When I submit the form, I see the html response packet is received in the browser (with firebug's net logs), but the html doesn't show up anywhere. Where should the html be? How to render a partial html view from an action?

highBandWidth
  • 16,751
  • 20
  • 84
  • 131

2 Answers2

1

you are rendering a partial but not specifying where to render it.

in rails 2 you could do it with:

def some_action
  # some logic
  render :update do |page|
    page.replace_html 'some_div_id', :partial => 'some_partial'
  end
end

but in rails 3, above code is no longer valid. see Unobtrusive Javascript

create a file named some_action.js.erb and write the code in it:

// update div with id some_div_id
$("#some_div_id").html("<%= escape_javascript(render :partial => 'some_partial') %>");

in controller

def some_action
  # some logic
  respond_to do |format|
    format.js
  end
end
shweta
  • 8,019
  • 1
  • 40
  • 43
  • yes, I know the problem is that I am not specifying where to render it. Is there any way to use render :partial inside an action to render an html view though? Perhaps with some way to determine where the html should go? – highBandWidth Feb 13 '13 at 06:52
  • you can specify where to render the html and other jquery stuff in some_action.js.erb, here some_action is your action name. – shweta Feb 13 '13 at 07:04
  • I understand that this is a workaround. My question is if there is any way to render a .html partial from an action. – highBandWidth Feb 13 '13 at 07:06
  • you can render a partial from controller but you can not update html elements from controller. – shweta Feb 13 '13 at 08:10
  • I guess you can actually send a .html.erb response, but you still need some js to actually put it in it's place. See my answer. – highBandWidth Mar 01 '13 at 21:08
0

I figured out how to send and display html. From theReq, just add :remote => true, "data-type" => "html" to the form and then in the javascript of the page, capture the returned html on ajaxSuccess to display it:

$('form#whatever').on('ajaxSuccess', function (event, data, status, xhr) {
    $('div#target').html(data);
  }
)
highBandWidth
  • 16,751
  • 20
  • 84
  • 131