Re: Returning JS in AJAX

David Teare
2005-06-02T01:59:45Z

Thanks Erik, that looks exactly like what I wanted to do.  The use case
I was planning on was exactly what you suspected - I wanted to update
multiple items on the screen from a single ajax request.

The other thing I have been interested in for a while is being able to
have my own JS code handle the result from the ajax request and display
it (or store it), instead of just always putting it into a div.  I never
saw Ajax.Request used directly before, but now I see how easy it is to
have full control over the response (but likely 90% of the time the
convience method Ajax.Updater will be used).

Thanks!

Erik Hatcher wrote:

>
> 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
>
> _______________________________________________
> Rails mailing list
> Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
> http://lists.rubyonrails.org/mailman/listinfo/rails