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 :

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

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

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.

#controller
def relations   
  component = Component.find(params[:id], :include => relations)
  @my_array = "js_variable= new Array(" + components.relations.map{ |r| r.id }.join(", ") + ")"
  #should produce a string like: "js_variable = new Array(1, 2, 3, 46, 9, 100);"
  respond_to do |format|
    format.js
  end
end
#relations.rjs
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 = @component.relations.map{ |t| t.id }
respond_to do |format|
     format.html
   format.js {   
     render :json => { :relations => relations }.to_json
     }
end

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