Magazine
 
Quick Review:Ajax
 
Automate data entry with Web servsices and Ajax
 

<%= text_field ‘address’, ‘state’ %></p>

It would be nice to be able to leave the city and state in the same file as the other address fields. I tried to get it to work but was only able to make it work this way. Why? The difficulty has to do with updating multiple form fields with the response from the Ajax call. Either my experience level with RoR is insufficient, or the generated JavaScript code can’t handle it. Most likely the former. Listing 3 shows the code for the _form.rhtml partial after removing the city and state input fields. Note that the new code is given an id = “ajaxLookup”; this is explained in the next step.

Listing 3. Including the new partial (_form.rhtml)

<%= error_messages_for ‘address’ %>
<p><label for=”address_street”>Street</label><br/>
<%= text_field ‘address’, ‘street’ %></p>
<p><label for=”address_zip5">Zip5</label><br/>
<%= text_field ‘address’, ‘zip5’, :size => “9”, :maxlength => “5” %></p>
<div id = “ajaxLookup”>
<%= render :partial => “cityStateFields” %>
</div>

The naming convention is an important idea in RoR. RoR assumes that partials are named with a leading underscore. And RoR assumes that references to that partial won’t contain an underscore. So in Listing 3, it’s expected that the line won’t have an underscore: <%= render :partial => “cityStateFields” %> is correct. RoR sees this line and looks in the same directory for a file named _cityStateFields.rhtml.

Step 3: Listen for changes to the ZIP code
Rails has built-in support for Ajax. This is one of the areas where Rails really shines. Simply add the lines of code shown in Listing 4 to listen for changes to the ZIP code field. Listing 4. Add an Ajax Listener to ZIP code (_form.rhtml)

01 <%= javascript_include_tag :defaults %>
02
03 <p><label for=”address_street”>Street</label><br/>
04 <%= text_field ‘address’, ‘street’ %></p>
05
06 <p><label for=”address_zip5">Zip5</label><br/>
07 <%= text_field ‘address’, ‘zip5’, :size => “9”, :maxlength => “5” %></p>
08
09 <div id = “ajaxLookup”>
10 <%= render :partial => “cityStateFields” %>
11 </div>
12
13 <%= observe_field :address_zip5,
14 :frequency => 2.00,
15 :update => “ajaxLookup”,
16 :url => {:action => :cityStateSearch, :id => @address},
17 :with => “‘zip5=’ + encodeURIComponent(value)”

June 2008 | Java Jazz Up | 17
 
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,   Download PDF