How to Include HTML in a Js Rails Response

How to include html tags in a js response in ajax call in Rails

In create action, it is not needed to type @result.html_safe, because it's actually does nothing here. Instead, you would like probably to tell your controller not to render layout.

def create
# ...
respond_to do |format|
format.html { render 'new' }
format.js { render layout: false }

end
end

Then, within create.js.erb:

$("p.bg-danger").html('<%=j @result %>');

Rails: rendering html and js in one request

A rails controller action can only respond to one HTTP request at a time, and even if it could respond to more than one the JS is requested from the HTML the initial request made any way (so it's a separate request).

If you'd like to keep your Javascript in another file for clarity you could create a partial and load it in that way.

In the view that responds to the controller action with @my_var passed to the partial (./views/mycontroller/my_action.html.erb):

<%= render 'my_action_js', :my_var => @my_var %>

And the partial (./views/mycontroller/_my_action_js.html.erb)

<script type="text/javascript">
alert(<%= my_var %>);
</script>

Is it possible to return HTML (instead of JS) data by using a remote link?

In order to require HTML code as response to an AJAX request you should add the :data => { :type => :html } to the link_to statement, this way:

link_to "Title", url, :remote => true, :data => { :type => :html }

The Rails jquery_ujs is aware of how to handle that.



Related Topics



Leave a reply



Submit