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.

7
  • 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. Commented Nov 11, 2014 at 14:13
  • @japed, this function call from another javascript function Commented Nov 11, 2014 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. Commented Nov 11, 2014 at 14:26
  • There's got to be a canonical question for this by now. I can't seem to find it though. Commented Nov 11, 2014 at 14:27
  • 1
    possible duplicate of How to pass a javascript variable into a erb code in a js view? Commented Nov 11, 2014 at 14:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

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.