RJS + Dynamic Script Tags = AJAX Heaven

One problem that often comes up with Ajax services is that you can’t call them on a domain different from the one that served your page. This is true even across subdomains of the same parent domain. Sucks!

Yahoo has some very clever services that return JSON-formatted data, so you can call them with a Dynamic Script Tag (script tag where src attribute is set dynamically), and easily access the results in Javascript. This is a great way to get around the cross-domain security controls of the XMLHttpRequest object.

This approach is nice for true services that return data, but in my case I wanted to return actual HTML, because the page edits I needed to make were pretty involved.

Fortunately, Rails JavaScript templates come to the rescue. RJS is a clever mechanism that generates Javascript code server side to be passed to the client and applied to the page. Well one of the functions included takes an arbitrary chunk of html and returns it as Javascript to generate that html. Perfect!

The net result is that it’s incredibly easy to convert my old Ajax call into a Dynamic Script Tag call.

Here’s the old client side code:

new Ajax.Updater(‘mydiv’, ‘/site/search?site=<%= site %>&q=<%= @q%>’, {asynchronous:true, evalScripts:true});

And here’s the new client code:

<script id=”rjs_target”></script>
<script>
$(‘rjs_target’).src =  ‘/site/search?site=<%= site %>&q=<%= @q%>&output=json’;
</script>

And then the magic on the server side:

if params[:output] == ‘json’
render(:update) {|page| page.replace_html @site, :partial => ‘webresults’ }
else
render :partial => ‘webresults’
end

The magic is in the page.replace_html call, which wraps the html generated by my partial into Javascript code.

The beauty is that this code uses my old partial exactly as-is. But this call can be served by any server I want. Whoo hoo!

1 comment so far

  1. emoticon prime on

    Got something like that going here (live search):

    http://channelsurfr.com/

    don’t know how I’d live without Rails…!


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: