2

I am working on one script which has been called from the websocket . This page of code is of html.erb

It pass variable to the javascript, and from that javascript variable i want to assign it to ruby variable ,

Here is the code

function set_color(val1,val2)
{

  <%background_color_id = %>
  var obj_color_id = '<%=background_color_id ='+val2+'%>' ;
  console.log(obj_color_id)
 }

The result from console log is +val2+

If I pass var obj_color_id = '<%=background_color_id ='val2'%>' ;

The result from console log is val2

Please help me assign javascript variable to ruby variable

1
  • try var obj_color_id = 'background_color_id<%='val2'%>' ; Commented Aug 22, 2012 at 6:25

3 Answers 3

3

You cannot do this. Javascript runs Client side, Ruby runs Server side.

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

2 Comments

this Page is html.erb page and i need to assing javascript variable to ruby variable
You cannot do this. If you want to assign data from the client (Javascript) to the Server (Ruby), you need to send data through requests like Ajax.
1

You can't do that. All values <%= are translated on server side and their values are send to client. There is no ruby on client side. You have to send request to your websocket or http server in order to pass some data to server.

2 Comments

this Page is html.erb page and i need to assing javascript variable to ruby variable
As I said, you cannot do this. Just send your variable via websocket or post request to you server..
0

Actually, if I understand your code (your question is not well phrased, unfortunately), the simple solution is:

1- Assign a value via server-side code:

function set_color(val1,val2)
{
  var bkgdColorId = "<%= background_color_id %>";
  var obj_color_id = bkgdColorId;
  console.log(obj_color_id)
}

2- (Or,) Assign a value from client-side code:

function set_color(val1,val2)
{
  /** pseudo-code **/
  on-click-event: makeAjaxCallToServer(){
    urlForWebService, { color: val2 }
  }
}

Using some jQuery (if assigning to server from client-side event) would greatly facilitate this process.

2 Comments

I have solved it via ajax call, but is there any way to just pass the value from client side javasscript value to server variable? like <%=background_color_id ='+val2+'%>
No. That's not possible since all server-side code is processed before the client (web browser) can evaluate the JavaScript (variables). You could, however, build a server-side web service (php file?) that works just like a form post (or get) and received a value that javascript posts to it. You would use an AJAX call to do this (or submit a form to the server).

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.