1

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?

3
  • You'd wrap the JS in a conditional/value rendered by the action. Commented Jun 23, 2018 at 12:27
  • @DaveNewton, something like render empty span with some id, and if it exists run js code? Commented 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. Commented Jun 23, 2018 at 13:41

3 Answers 3

4

In your view file

<% if params[:alert] %>

<script>alert("Hello");</script>

<% end %>
Sign up to request clarification or add additional context in comments.

Comments

0

You can always do in your controller:

def some_action
 if condition
  @run_javascript = true
 else
  @run_javascript = false
 end
end

and then in your view

<script type="text/javascript">
 <% if @run_javascript %>
  alert('Something was wrong');
 <% end %>
</script>

Comments

0
#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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.