0

I have such script inside my html.erb:

if(browser == "Firefox") {
  $(".browser-warning").show();
}

else if(browser == "Safari") {
  if(browser.version < 6) {
    $(".browser-warning").show();
  }
}

else if((BrowserDetect.browser != "Chrome") && (<%= params[:section_id].to_s %> != '')) {
  console.log('yo');
  <%= session[:is_chrome] = false %>
  <%= Rails.logger.debug = "I made is_chrome false, wtf?" %>
}

else {
  $(".browser-warning").show();
}

I'm running this script from Chrome browser and condition returns false.

but session[:is_chrome] is always becomes false and Rails logger returns "I made is_chrome false, wtf?". BUT. JS console logger don't print "yo" in console. Why it's so and what is proper way to define session value only when JS "if" statement is true?

Thanks, all.

3
  • Are you trying to evaluate something on the server based on a value on the client? Commented Oct 23, 2014 at 18:56
  • @Mathletics yes, I'm. Commented Oct 23, 2014 at 18:57
  • 2
    Yeah, you can't do that, you know? Because the Ruby has already been evaluated by on the server by the time the JS is run on in the browser. Commented Oct 23, 2014 at 19:03

3 Answers 3

5

On the server while rendering your template every ruby snippet gets evaluated.
So also these lines gets executed on the server (every time, not only if it's not a chrome browser):

<%= session[:is_chrome] = false %>
<%= Rails.logger.debug = "I made is_chrome false, wtf?" %>

To get around this you can do one the following:

  • Check on the server if it's an chrome browser and make the necessary changes
  • Check on the client if it's an chrome browser an make an ajax call to the server to inform that there is an chrome (or non chrome) browser


In addition put <%= params[:section_id].to_s %> in quotes (as user "infused" also stated):

"<%= params[:section_id].to_s %>"
Sign up to request clarification or add additional context in comments.

Comments

2

You need to understand that rails is rendering erbs before they are being send to the browser, and there is no erb statements when javascript is running its code. In addition, when rails is rendering the file, it treats everything not surrounded by <% %> as a pure text, so both

<%= session[:is_chrome] = false %>
<%= Rails.logger.debug = "I made is_chrome false, wtf?" %>

are always executed, regardless of what kind of javascript code is written around them.

If you want to execute some server-side code client-side, the only way to do this is to send another request (via Ajax, easy option), or use socketIO to enable client-server communication (never done it by myself :()

However what you're trying to achieve is possible to be achieved strictly on server side: have a look at this question

Comments

0

You need to put quotes around the Ruby output:

"<%= params[:section_id].to_s %>"

Comments

Your Answer

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