Filling an address field with Ajax

Within the main address editing form I have the following:

<%= text_field_tag :postcode %><%= submit_to_remote "addressSearch", "Search",  :url => {:action => 'lookup_postcode'},  :with => "'postcode='+postcode.value",  :update => :addressLookupResults%>

Results are then rendered via a partial as follows:

def lookup_postcode  @results = PostcodeLookup.find("SW1A 1AA")  render_partial("postcode_results")end

The results partial looks as follows:

<%= select_tag(  :selected_address,  options_for_select(    @results.map{|a| [a.description, a.address_id]},  '')  )%><%= submit_to_remote "selectAddress",  "Use",  :url => {:action => 'fill_address'},  :with => "'selected_address='+selected_address.value",%>

Upon a user pressing the button, the `fill_address` action will be invoked, and selected_address will be passed through. Now, for the magic (courtesy of RJS templates):

def fill_address  address = PostcodeLookup.get_address(    params[:selected_address]  )end

@address = Address.new(  :line_1 => address.line_1,  :line_2 => address.line_2,  :town => address.town,  :county => address.county,  :postcode => address.postcode  )

render :update do |page|  page.hide('addressLookupResults')  page.replace_html(    'address',    :partial => 'address'  )end

The significant stuff happens during the render method call. This generates JavaScript which is emitted to the browser, which when executed will replace the address entry section of the HTML with updated HTML containing the newly filled address fields.

So far it works quite well, but, as mentioned in a few places it does lead to relatively unsightly markup. Not that much of a problem in this situation as the physical impact on the rendered code isn’t that large. In a results page, it would perhaps be more significant.

The complaint seems to be a more theoretical one—that JavaScript shouldn’t belong in the markup, which is something a commenter (Jonathan Conway) on my previous post also mentioned.

I think there’s a tendency towards some people becoming quite millitant over these kinds of things, but I can fully appreciate that one bad step at the beginning can easily evolve into a messy, inelegant codebase that you don’t want to work with, and users don’t like having to consume.

So, my next step is to wrap this stuff up with Behaviour.js and improve my CSS knowledge a little and improve my code quality before I get too far into Ajax land!