0

In my RoR project I got html page, where I changing div's background image with javascript. Javascript function send me index, and I want to use this index for getting element of ruby array.

Look into my code

function drawNewProject (index){
  console.log(<%= 'index' %>)
  <% index = 'index'  %>
  <% @existProjects = Admin::Project.order('weight') %>
  <% @existProject = @existProjects[index] %>

  var image = document.getElementById('block_one')

  image.style.backgroundImage="url('<%=  @existProject.image(:large) %>')";

}

But this line

<% @existProject = @existProjects[index] %>

Gives me error

no implicit conversion of String into Integer

Do you know how to do it correct? Thnx.

Eugene Trapeznikov
  • 3,220
  • 6
  • 47
  • 74
  • 2
    `<% index = 'index' %>` is just setting the variable index to the string index. You're going to need to make an ajax request to a controller passing the index to it then returning the Project so you can change the background image. – j-dexx Nov 11 '14 at 14:13
  • @japed, this function call from another javascript function – Eugene Trapeznikov Nov 11 '14 at 14:22
  • That doesn't matter, you're still going to need to make an ajax request which you can do in this method. – j-dexx Nov 11 '14 at 14:26
  • There's got to be a canonical question for this by now. I can't seem to find it though. – Ajedi32 Nov 11 '14 at 14:27
  • FYI, this problem stems from a fundamental misunderstanding of the way ERB works. ERB just fills in the blanks before sending the script to the browser. It can't get information out of JavaScript variables, since as far as it is concerned that's not even JavaScript: just a lump of text that it's about to send to the user's browser. – Ajedi32 Nov 11 '14 at 14:30
  • @japed can you provide sample code for ajax request and for controller method? – Eugene Trapeznikov Nov 11 '14 at 14:30
  • 1
    possible duplicate of [How to pass a javascript variable into a erb code in a js view?](http://stackoverflow.com/questions/4959770/how-to-pass-a-javascript-variable-into-a-erb-code-in-a-js-view) – Ajedi32 Nov 11 '14 at 14:34

1 Answers1

0

You have to think that the <%= erb %> block is executed in the server before being sent to the browser, and once there, the javascript is run.

Your browser has no idea about ruby or php or whatever... it just receives the html and the js (regardless is a static file, or a dynamically generated bunch of js) and runs it.

That means that all the data must be known at rendering time. If your application depends on dynamic data, or on your user interaction, then you have to do an ajax request and deliver back a call with the right js to be run by the browser.

Fer
  • 3,247
  • 1
  • 22
  • 33