Re: Returning JS in AJAX

Erik Hatcher
2005-06-02T01:38:58Z

On Jun 1, 2005, at 9:07 PM, David Teare wrote:

>
> I have Ajax working fine to return html code and display it in a
> div.  Now, I would like to return some JavaScript generated in the
> controller, and have this execute in the browser.  I tried
> assigning the script code to a div, which successfully put the
> script into the div, but the code is never executed.
>
> What I would like is something like DWR (http://getahead.ltd.uk/
> dwr/) that allows you to define a JS function that will be executed
> with the returned ajaxed data.  Is this possible in Rails?  I can
> port over the DWR code, but I don''t want to reinvent the wheel.

I have fun learning things by attempting to answer.  I quickly hacked
this together:

View:
     <input type="button"
onclick="test(''client'')"/>

     function test(val) {
       var opts = {
         parameters: "param=" + val,
                      onComplete: function(data) {
                         eval(data.responseText);
                      }
       };
       var req = new Ajax.Request(''/controller/test'', opts);
      }


Controller:
   def test
      render_text "alert(''#{@params[:param]} ->
server'');"
   end

Don''t take this as _the_ way to do it, as I''m new to Rails and
the
mystical Prototype JavaScript additions, but this worked beautifully
on my first try.  I got a pop-up on my browser when I clicked the
button that said "client -> server".  I''d love to see what
others
have to say on this topic though.

Questions - why send JavaScript down?  What advantage is there to
doing?  I can envision it being useful to update multiple elements at
one time perhaps, but I''m curious what your use case is.

     Erik