Topic: Returning javascript variables

I would like to be able to return javascript variables when i call a specific controller method and then use these variables directly in my ajax request.

in my behaviours.js :

  '.component:click' : function(event){
    var element = Event.element(event);
    new Ajax.Request('components/'+parseInt(';relations', {method:'get',...});

in the components controller:
 def relations
   component = Component.find(params[:id])
   component.relations # turn this into a javascript array

I would like this method to return me a javascript array full of ids so that i can update the corresponding elements on my page. Does anyone know how to do that ?

Thanks for your help.

Re: Returning javascript variables

This might work, i assume you expect so receive javascript on the client side:

create a string of JS code and send it back with RJS.

def relations   
  component = Component.find(params[:id], :include => relations)
  @my_array = "js_variable= new Array(" +{ |r| }.join(", ") + ")"
  #should produce a string like: "js_variable = new Array(1, 2, 3, 46, 9, 100);"
  respond_to do |format|
page << @my_array

might be BS though as i'm not as familiar with plain JS AJAX as i would like to. wink

Last edited by Duplex (2007-08-27 10:48:21)

Re: Returning javascript variables

Thanks Duplex, your solution doesn't produce exactly what i expected as i get it in a "try{}". But instead i used the to_json method which returns me exactly what i wanted.(and no need for a rjs that way)

relations ={ |t| }
respond_to do |format|
   format.js {   
     render :json => { :relations => relations }.to_json

=> {relations: [1,2,3,4]}