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
Retrieve Dom Target from Drag Callback When 'This' Is Not Available
Why Does "True" == True Show False in JavaScript
Safari Web Extension - Injecting Script Only When Extension Button Is Clicked
How to Import Variables in JavaScript (Node.Js)
Linguistic Meaning of 'Let' Variable in Programming
How to Intercept Xmlhttprequests from a Greasemonkey Script
Which Ecmascript 6 Features Imply Strict Mode
Why am I Getting Weird Result Using Parseint in Node.Js? (Different Result from Chrome Js Console)
How to Split a Long Regular Expression into Multiple Lines in JavaScript
Creating a "Sticky" Fixed-Position Item That Works on iOS Safari
The .Replace() Method Does Change the String in Place
Rails Specify Load Order of JavaScript Files
Has Anyone Else Run into Problems Styling Twitter Typeahead's Searchbar
What's the Difference Between Returning Value or Promise.Resolve from Then()
Download a Div in a HTML Page as PDF Using JavaScript
Create an Object from an Array of Keys and an Array of Values