Module Tutorial: User Polling / Rating: Going Ajax

Now we’ve got a more-or-less useful poll system, but there’s one thing that’s a little painful. When a user submits a poll, the whole page has to reload before we see the result. What is this, 1998? Let’s add a little Ajax to make the user experience better.

Step 1: Update the paragraph to accept ajax calls

The first thing we need to do is to set our paragraph up to accept Ajax calls. This is pretty easy: just open up page_renderer.rb and modify the paragraph :view line (around line 6) to read:

vendor/modules/poll_demo/app/controllers/poll_demo/page_renderer.rb

   paragraph :view, :ajax => true

Step 2: Get us some Prototype

By default, Webiva tries to include as few Javascript files in a site a possible, so by default Prototype isn’t available on the front end of the website unless we explicitly include it. Since we’d have to be insane to try to do cross-browser Ajax without a base library, we need to include it. Modify the view method in page_renderer.rb by adding the following line right above the render_paragraph call:

vendor/modules/poll_demo/app/controllers/poll_demo/page_renderer.rb

         require_js('prototype')

This will make sure that the protoype.js file is included when the page renderers initially.

Step 3: Modifying the feature

Webiva now has Ajax support baked into features, so having the paragraph submit via ajax and is as simple as modifying the c.form_for_tag and replacing it with a c.ajax_form_for_tag

vendor/modules/poll_demo/app/controllers/poll_demo/page_feature.rb

           c.ajax_form_for_tag('form','poll') do |t|
              if data[:state] == 'question'
               { 
                 :object => data[:response],
                 :code => hidden_field_tag('poll[poll_demo_poll_id]',data[:poll].id)
               }
             end
           end

Now save all the files and test out your polls - you should see some nice Ajax functionality.