3

I have a controller with an action that is being hit remotely, after which my controller_action.js.erb file is run.

Within my controller's action, I am setting a variable @successful = true|false (true|false based on the return value of a function).

Within my javascript file, I want to say if @successful and either alert that the action was successful or alert that it was not.

Any idea how to do this?

2 Answers 2

2

try this

<%- if @successful %>
   alert('Blabla');
<%- else %>
   alert('Blabal');
<%- end %>
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, raphaelcm had the right answer in there first. This is mostly right, but a little ugly since you use rails if else instead of javascript's. Does <%- differ from <%= in any significant way? I have never seen the former before.
<%- doesn't render any output, while <%= does.
I thought to not render output you just use <% is that synonymous with <%-?
Ah, I wasn't entirely correct. <%- and -%> are like <% and %>, but also suppress leading and trailing whitespace. See: api.rubyonrails.org/classes/ActionView/Base.html
1

I speak HAML usually, so this might not be exactly correct:

if(<%= @successful %>) {
  // do stuff
} else {
  // do other stuff
}

In HAML, it would be:

:javascript
  if(#{@successful}) {
    // do stuff
  } else {
    // do other stuff
  }

Alternatively, you could do this:

(ERB)

<%- if @successful %>
  // JS code if true
<%- else %>
  // JS code if false
<%- end %>

(HAML)

- if @successful
  :javascript
    // JS code if true
- else
  :javascript
    // JS code if false

The first option will always render all your JS code on the client side, the only difference being if true or false is in the if clause.

The second option will conditionally only render the JS code for the true or false case.

4 Comments

The correct answer lies in this response. The first code block worked perfectly. If you could remove the superfluous stuff, you've got best answer.
A lot of people use HAML instead of ERB, seems useful to leave it in. Is there something incorrect I should remove/edit, or a reason you think the HAML is superfluous?
I added ERB for the second approach, and explained the difference between the two approaches.
I just thought it was superfluous because I'm not using it. Good point–someone may find it useful. I won't verify it, but I'll take your word for it. Thanks for the edit!

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.