How can I run javascript code based on some condition in a controller? For example, I want to display javascript alert, when params[:alert] is present. How can I do this?
-
You'd wrap the JS in a conditional/value rendered by the action.Dave Newton– Dave Newton2018-06-23 12:27:02 +00:00Commented Jun 23, 2018 at 12:27
-
@DaveNewton, something like render empty span with some id, and if it exists run js code?Marcin Doliwa– Marcin Doliwa2018-06-23 12:29:11 +00:00Commented Jun 23, 2018 at 12:29
-
Just render anything, it could be a scriptlet around a script tag (which works, but I think it's gross), a value in a JS block, anything. It doesn't matter. That said, native alerts are pretty awful anyway.Dave Newton– Dave Newton2018-06-23 13:41:28 +00:00Commented Jun 23, 2018 at 13:41
Add a comment
|
3 Answers
#view page
<script>
<% flash.each do |k,v| %>
<% if k == "success" %>
success("<%= v %>");
<% else %>
alert("<%= v %>")
<% end %>
<% end %>
</script>
You need only flash:{ alert: or success:}
#controller
respond_to do |format|
format.html{ redirect_back(fallback_location: '/orders', flash: { alert: "custom message" } ) }
end