ajax and camping, together at last

I had to mock up a demo for Intel for my work and went with _why’s Camping. However nobody on the IRC channel the other day knew how to use ajax with it. It turned out to be easy.

serve static files

You need your Camping app to be able to serve the javascript libraries to the client. Follow these instructions from the wiki. We have updated them recently to be more robust.

Once you actually deploy your app, it will be faster and more stable to serve the static directory either directly from Apache, or with a mongrel dirhandler. Both ways bypass your static camping controller. There is an example of the mongrel dirhandler in rv version 2.

require the javascript

Copy the Prototype and Scriptaculous javascript libraries out of a Rails installation, and require them in the head element of your layout.

in your layout method, in App::Views
head do
  ['prototype', 'effects', 'controls'].each do |s|
    script :src => "/static/#{s}.js", :type => 'text/javascript'

make a link

Make a link in one of your views that will call the ajax’ed action and specify the element to update with the response.

in your view method, in App::Views
id = "some_element"
onclick = "new Ajax.Updater('#{id}', '#{URL(MyAction, some_parameter)}',
           {asynchronous:true, evalScripts:true}); return false;"
a "Link text",
  :id => id,
  :href => R(NoJavascriptFallbackAction, some_parameter),
  :onClick => onclick                

return something

Then have your action just return a raw string instead of calling render:

in App::Controllers
class MyAction < R '/myaction/(.*)'
  def post param
    # do something with param

the Ajax.Updater will replace the element you specified with the action’s response.

Or a feral cat. Mepw.

One response