<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>nealenssle.com &#187; code</title>
	<atom:link href="http://nealenssle.com/blog/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://nealenssle.com/blog</link>
	<description></description>
	<lastBuildDate>Tue, 27 Sep 2011 11:39:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How to sort query results using a SELECT clause in the ORDER BY</title>
		<link>http://nealenssle.com/blog/2011/05/23/order-by-with-select/</link>
		<comments>http://nealenssle.com/blog/2011/05/23/order-by-with-select/#comments</comments>
		<pubDate>Tue, 24 May 2011 02:20:58 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[untagged]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[databases]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/?p=398</guid>
		<description><![CDATA[The other day I needed to order a SQL query using by a value derived from a sub-query. Turns out it&#8217;s pretty straightforward:

SELECT *
FROM posts
ORDER BY (SELECT last_name FROM comments WHERE post_id = posts.id) DESC;

The ORDER BY clause will use whatever&#8217;s returned from the subquery to order things.
]]></description>
			<content:encoded><![CDATA[<p>The other day I needed to order a SQL query using by a value derived from a sub-query. Turns out it&#8217;s pretty straightforward:</p>
<pre>
SELECT *
FROM posts
ORDER BY (SELECT last_name FROM comments WHERE post_id = posts.id) DESC;
</pre>
<p>The ORDER BY clause will use whatever&#8217;s returned from the subquery to order things.</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2011/05/23/order-by-with-select/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to pick a random element from an Array</title>
		<link>http://nealenssle.com/blog/2011/02/28/how-to-pick-a-random-element-from-an-array/</link>
		<comments>http://nealenssle.com/blog/2011/02/28/how-to-pick-a-random-element-from-an-array/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 13:44:30 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[untagged]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/?p=391</guid>
		<description><![CDATA[Here&#8217;s a nifty little patch to Ruby&#8217;s Array class to provide a method for picking an element at random:

class Array
  def random_pick
    self.sort_by { rand }.first
  end
end

So then you can do things like this:

def what_is_your_favorite_color?
  colors = [ 'red', 'blue', 'green', 'yellow', 'purple', 'pink', 'black' ]
  colors.random_pick
end

Please don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a nifty little patch to Ruby&#8217;s Array class to provide a method for picking an element at random:</p>
<pre>
class Array
  def random_pick
    self.sort_by { rand }.first
  end
end
</pre>
<p>So then you can do things like this:</p>
<pre>
def what_is_your_favorite_color?
  colors = [ 'red', 'blue', 'green', 'yellow', 'purple', 'pink', 'black' ]
  colors.random_pick
end
</pre>
<p>Please don&#8217;t ask my why I&#8217;m doing this. The answer has something to do with test data. </p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2011/02/28/how-to-pick-a-random-element-from-an-array/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Teaching clean code principles via de-factoring?</title>
		<link>http://nealenssle.com/blog/2010/09/06/teaching-clean-code-via-defactoring/</link>
		<comments>http://nealenssle.com/blog/2010/09/06/teaching-clean-code-via-defactoring/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 17:36:07 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[untagged]]></category>
		<category><![CDATA[better]]></category>
		<category><![CDATA[cleancode]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[ideas]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/?p=345</guid>
		<description><![CDATA[Here&#8217;s a new idea (to me, at least): Teach clean coding principles by starting with some very readable, very clean code. Then refactor (defactor) it into an incomprehensible, indecipherable quagmire of messy awfulness.
Why? The topic of &#8220;clean code&#8221; is a tough one to teach. Ask a random sampling of programmers and you&#8217;ll probably get a [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a new idea (to me, at least): Teach clean coding principles by starting with some very readable, very clean code. Then refactor (defactor) it into an incomprehensible, indecipherable quagmire of messy awfulness.</p>
<p>Why? The topic of &#8220;clean code&#8221; is a tough one to teach. Ask a random sampling of programmers and you&#8217;ll probably get a wide variety of opinions about what constitutes &#8220;clean&#8221; or readable code. Everybody has their likes, dislikes, and preferred idioms. And when we start with code that seems &#8220;bad&#8221; and try to talk about what &#8220;cleaner&#8221; code would look like we often end up talking in circles, debating what &#8220;good&#8221; code really means.</p>
<p>So in effort to avoid letting the perfect become the enemy of the good, I&#8217;m thinking it might make sense to try to play around a bit with de-factoring as a tool. Let&#8217;s see how it works if we start with something we might call clean, and then work to make it much worse, talking about what it is that makes it worse along the way.</p>
<p>Stay tuned. There&#8217;s hopefully more to follow on this topic!</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2010/09/06/teaching-clean-code-via-defactoring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to find the name of the current Rake task</title>
		<link>http://nealenssle.com/blog/2009/11/14/how-to-find-the-name-of-the-current-rake-task/</link>
		<comments>http://nealenssle.com/blog/2009/11/14/how-to-find-the-name-of-the-current-rake-task/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 03:15:59 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[untagged]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rake]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/?p=161</guid>
		<description><![CDATA[A few weeks ago I needed a Rake task to answer a simple question for me:
&#8220;What&#8217;s my name?&#8221;
I honestly can&#8217;t quite remember why exactly the task needed to know it&#8217;s own name, but at the time it seemed important and I spent a couple hours digging about before I found out that Rake tasks are [...]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago I needed a Rake task to answer a simple question for me:</p>
<p>&#8220;What&#8217;s my name?&#8221;</p>
<p>I honestly can&#8217;t quite remember <em>why exactly</em> the task needed to know it&#8217;s own name, but at the time it seemed important and I spent a couple hours digging about before I found out that Rake tasks are shy by nature. Or at least when implemented the way almost every tutorial tells you to implement them:</p>
<pre>
namespace :life do

  desc "The answer to life, the universe, and everything"
  task :answer do
    puts "The answer to life, the universe, and everything is 42."
  end

end
</pre>
<p>But how do I know what the name of the current task is?  Well, after making a couple of random attempts (like &#8220;puts task.name&#8221;) and digging around in the <em>very sparse</em> documentation on the <a href="http://rake.rubyforge.org/">Rake homepage</a>, I stumbled  across a bit of documentation that talked about &#8220;Tasks with Actions&#8221;:</p>
<blockquote><p>
Actions are defined by passing a block to the task method. Any Ruby code can be placed in the block. The block may reference the task object via the block parameter.</p>
<pre>
task :name => [:prereq1, :prereq2] do |t|
  # actions (may reference t)
end
</pre>
</blockquote>
<p>Ah ha! &#8220;The block may reference the task object via the block parameter.&#8221;  That&#8217;s exactly what I was looking for.  Adding the block parameter allows us to reference the task object itself. And the task object itself has a good bit of useful meta information:</p>
<pre>
namespace :life do

  desc "The answer to life, the universe, and everything"
  task :answer do |t|
    puts t.name
    puts t.comment
    puts t.scope
  end

end
</pre>
<p>The task now returns the following:</p>
<pre>
life:answer
The answer to life, the universe, and everything
life
</pre>
<p>The first line of output is nifty, and answers the &#8220;What&#8217;s my name?&#8221; question with the fully scoped name of the task. Given that much it&#8217;s probably not hard to return the task name in even the most deeply namespaced Rakefile. The second line is the &#8220;comment&#8221; &#8212; actually the description of the task.  And the third line gets us the scope (namespaces). There are more methods available, but check teh googles for &#8220;Rake::Task api&#8221;.</p>
<p>So with this meta information we can do something useful like:</p>
<pre>
namespace :life do

  desc "The answer to life, the universe, and everything"
  task :answer do |t|
    puts "#{t.comment} is 42."
  end

end
</pre>
<p>Voila. And that&#8217;s probably enough meta for one day.</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2009/11/14/how-to-find-the-name-of-the-current-rake-task/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to filter Subversion logs by date and author</title>
		<link>http://nealenssle.com/blog/2009/10/14/how-to-filter-subversion-logs-by-date-and-author/</link>
		<comments>http://nealenssle.com/blog/2009/10/14/how-to-filter-subversion-logs-by-date-and-author/#comments</comments>
		<pubDate>Thu, 15 Oct 2009 03:43:02 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[untagged]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scm]]></category>
		<category><![CDATA[subversion]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/?p=123</guid>
		<description><![CDATA[I keep forgetting this snippet, and then spend hours re-discovering/re-inventing it. So for the record: Here&#8217;s a bit of magic to let you filter your Subversion (SVN) logs by date and author:

svn log -vr {20091014}:"HEAD" &#124; sed -n "/nealenssle/,/-----$/ p"

I use it in a bash shell script function that I&#8217;ve got in my .bash_profile script [...]]]></description>
			<content:encoded><![CDATA[<p>I keep forgetting this snippet, and then spend hours re-discovering/re-inventing it. So for the record: Here&#8217;s a bit of magic to let you filter your Subversion (SVN) logs by date and author:</p>
<pre>
svn log -vr {20091014}:"HEAD" | sed -n "/nealenssle/,/-----$/ p"
</pre>
<p>I use it in a bash shell script function that I&#8217;ve got in my .bash_profile script like so:</p>
<pre>
function svnlog {
    svn log -vr {$1}:"HEAD" | sed -n "/$2/,/-----$/ p"
}
</pre>
<p>And then call it like so:</p>
<pre>
svnlog 20091014 nealenssle
</pre>
<p>Happy spelunking!</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2009/10/14/how-to-filter-subversion-logs-by-date-and-author/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to create Rails scaffolds and database tables dynamically</title>
		<link>http://nealenssle.com/blog/2008/10/10/how-to-create-rails-scaffolds-and-database-tables-dynamically/</link>
		<comments>http://nealenssle.com/blog/2008/10/10/how-to-create-rails-scaffolds-and-database-tables-dynamically/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 12:25:07 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/2008/10/10/how-to-create-rails-scaffolds-and-database-tables-dynamically/</guid>
		<description><![CDATA[The idea I&#8217;m exploring here is whether or not we can build a CMS (content management system) in Ruby on Rails that can dynamically build a CMS.  In other words, can we write Rails code that writes Rails code.
It seems we can. This is pretty awesome, and somewhat frightening, because it apparently works.  [...]]]></description>
			<content:encoded><![CDATA[<p>The idea I&#8217;m exploring here is whether or not we can build a CMS (content management system) in Ruby on Rails that can dynamically build a CMS.  In other words, can we write Rails code that writes Rails code.</p>
<p>It seems we can. This is pretty awesome, and somewhat frightening, because it apparently works.  Here&#8217;s a method in, say, a &#8220;utils_controller.rb&#8221;:</p>
<pre>def generate_scaffold
    @results = `script/generate scaffold
    Things name:string value:string`
end</pre>
<p>Note the use of backticks around the shell commands to generate a scaffold.  If you run that method in your browser, it actually generates the controller, model, migration, etc.</p>
<p>Then do this:</p>
<pre>def migrate
    @results = `rake db:migrate`
end</pre>
<p>Yep.  Now you just migrated the database and have new &#8220;things&#8221; table.</p>
<p>Eureka?</p>
<p>Obviously some issues here (like&#8230; OMGWTF!  Run away!  Do not try this at home!).  But I&#8217;m a little bit excited&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2008/10/10/how-to-create-rails-scaffolds-and-database-tables-dynamically/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to turn a string into CamelCase in Ruby</title>
		<link>http://nealenssle.com/blog/2007/07/21/how-to-turn-a-string-into-a-wikiword-in-ruby/</link>
		<comments>http://nealenssle.com/blog/2007/07/21/how-to-turn-a-string-into-a-wikiword-in-ruby/#comments</comments>
		<pubDate>Sun, 22 Jul 2007 03:09:24 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/2007/07/21/how-to-wikify-a-string-in-ruby/</guid>
		<description><![CDATA[Here&#8217;s a function to turn any given string into a CamelCase &#8220;WikiWord&#8221; in Ruby:

def wikify(phrase)
  phrase.gsub!(/^[a-z]&#124;\s+[a-z]/) { &#124;a&#124; a.upcase }
  phrase.gsub!(/\s/, '')
  return phrase
end

Voila.  This turns &#8220;my dog has fleas&#8221; into &#8220;MyDogHasFleas&#8221;.  
Note: I&#8217;m sure there&#8217;s a way to fix this so that it&#8217;s just one regular expression?  Feel [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a function to turn any given string into a <a href="http://en.wikipedia.org/wiki/CamelCase">CamelCase</a> &#8220;WikiWord&#8221; in Ruby:</p>
<pre>
def wikify(phrase)
  phrase.gsub!(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
  phrase.gsub!(/\s/, '')
  return phrase
end
</pre>
<p>Voila.  This turns &#8220;my dog has fleas&#8221; into &#8220;MyDogHasFleas&#8221;.  </p>
<p>Note: I&#8217;m sure there&#8217;s a way to fix this so that it&#8217;s just one regular expression?  Feel free to chime in!</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2007/07/21/how-to-turn-a-string-into-a-wikiword-in-ruby/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>How to dynamically update form elements in Rails using Ajax</title>
		<link>http://nealenssle.com/blog/2007/04/12/how-to-dynamically-update-form-elements-in-rails-using-ajax/</link>
		<comments>http://nealenssle.com/blog/2007/04/12/how-to-dynamically-update-form-elements-in-rails-using-ajax/#comments</comments>
		<pubDate>Thu, 12 Apr 2007 12:15:34 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/2007/04/12/how-to-dynamically-update-form-elements-in-rails-using-ajax/</guid>
		<description><![CDATA[Here&#8217;s the situation: You have two SELECT elements on a form.  When the user chooses an item out of the first SELECT element, the contents of the second SELECT element need to change and show different values based on the initial selection.
This used to take quite a bit of JavaScript wizardry.  But it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the situation: You have two SELECT elements on a form.  When the user chooses an item out of the first SELECT element, the contents of the second SELECT element need to change and show different values based on the initial selection.</p>
<p>This used to take quite a bit of JavaScript wizardry.  But it&#8217;s pretty straightforward in Rails using a bit of Ajax.  Here&#8217;s how:</p>
<p>First, make sure you&#8217;re including the Ajax libraries (Prototype, script.aculo.us, etc.) in your layout like so:</p>
<pre>
&lt;html&gt;
&lt;head&gt;
       &lt;%= javascript_include_tag :defaults %&gt;
&lt;/head&gt;
&lt;body&gt;
...
</pre>
<p>Next, create a form with your initial SELECT, and empty second SELECT, and set up field observer.  Here&#8217;s a really simple example:</p>
<pre>
&lt;form&gt;

&lt;select id=&quot;states&quot; name=&quot;states&quot;&gt;
    &lt;option value=&quot;0&quot;&gt;&lt;/option&gt;
    &lt;option value=&quot;1&quot;&gt;Colorado&lt;/option&gt;
    &lt;option value=&quot;2&quot;&gt;Illinois&lt;/option&gt;
    &lt;option value=&quot;3&quot;&gt;Wyoming&lt;/option&gt;
&lt;/select&gt;

&lt;%= observe_field &quot;states&quot;, :update =&gt; &quot;cities&quot;,
:with =&gt; &quot;city_id&quot;, :url =&gt; { :controller =&gt; &quot;test&quot;,
:action =&gt; &quot;get_cities&quot; } %&gt;

&lt;br /&gt;

&lt;select id=&quot;cities&quot; name=&quot;cities&quot;&gt;
    &lt;option&gt;&lt;/option&gt;
&lt;/select&gt;

&lt;/form&gt;
</pre>
<p>Finally, you&#8217;ll need to set up a method to handle the call from the observer and a corresponding view page to generate the HTML content that will replace everything betwen the SELECT tags in the second SELECT.  Here&#8217;s an example &quot;get_cities&quot; controller:</p>
<pre>
def get_cities
    @cities = City.find_by_state(:all)
end
</pre>
<p>And an example &quot;get_cities.rhtml&quot; file:</p>
<pre>
&lt;% for city in @cities %&gt;
    &lt;option value=&quot;&lt;%= city.id %&gt;&quot;&gt;&lt;%= city.name %&gt;&lt;/option&gt;
&lt;% end %&gt;
</pre>
<p>And there you go.  This much should dynamically update the &quot;cities&quot; SELECT element with new content every time the &quot;onchange&quot; event is fired on the initial &quot;states&quot; SELECT form element.</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2007/04/12/how-to-dynamically-update-form-elements-in-rails-using-ajax/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>How to define multiple users in a Capistrano deployment file</title>
		<link>http://nealenssle.com/blog/2007/04/11/how-to-define-multiple-users-in-a-capistrano-deployment-file/</link>
		<comments>http://nealenssle.com/blog/2007/04/11/how-to-define-multiple-users-in-a-capistrano-deployment-file/#comments</comments>
		<pubDate>Wed, 11 Apr 2007 11:36:52 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/2007/04/11/defining-multiple-users-in-a-capistrano-deployment-file/</guid>
		<description><![CDATA[We&#8217;re just starting to get into Ruby on Rails at my work, and we&#8217;re close to deploying our first application to a production server with Capistrano.  
Capistrano makes it easy for developers to deploy code to the production server from their own workstations.  But we quickly ran into two problems:

It&#8217;s often the case [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re just starting to get into <a href="http://www.rubyonrails.org">Ruby on Rails</a> at my <a href="http://foraker.com">work</a>, and we&#8217;re close to deploying our first application to a production server with <a href="http://manuals.rubyonrails.com/read/book/17">Capistrano</a>.  </p>
<p>Capistrano makes it easy for developers to deploy code to the production server from their own workstations.  But we quickly ran into two problems:</p>
<ol>
<li>It&#8217;s often the case that a developer&#8217;s username on their local workstation is different from their username on the production server.  This requires you to set the developer&#8217;s server username in the &#8220;deploy.rb&#8221; file.  Hard-coded.</li>
<li>Hard-coding a single username makes it difficult for multiple users to share a &#8220;deploy.rb&#8221; file.
</ol>
<p>Well, it turns out that Capistrano is better than all that.  With a little bit of conditional logic and the ability for Cap to read environment variables, the problem is solved like this in the &#8220;deploy.rb&#8221; file:</p>
<pre>
if ENV["USER"] == "robert"
    set :user, "bob"
elsif ENV["USER"] == "elizabeth"
    set :user, "beth"
end
</pre>
<p>Voila.</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2007/04/11/how-to-define-multiple-users-in-a-capistrano-deployment-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to roll your own Ajax</title>
		<link>http://nealenssle.com/blog/2006/09/26/simple-ajax/</link>
		<comments>http://nealenssle.com/blog/2006/09/26/simple-ajax/#comments</comments>
		<pubDate>Tue, 26 Sep 2006 11:54:52 +0000</pubDate>
		<dc:creator>Neal Enssle</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nealenssle.com/blog/2006/09/26/simple-ajax/</guid>
		<description><![CDATA[A little while ago I decided I needed to get my head around this whole &#8220;Ajax&#8221; thing.  From Wikipedia:
Ajax, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server [...]]]></description>
			<content:encoded><![CDATA[<p>A little while ago I decided I needed to get my head around this whole &#8220;Ajax&#8221; thing.  From <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29">Wikipedia</a>:</p>
<blockquote><p>Ajax, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page&#8217;s interactivity, speed, and usability.</p></blockquote>
<p>Mainly it was for a couple of issues we were having at work, but I&#8217;ve <a title="ColdFusion Developer's Journal: HTTP status code 204" href="http://coldfusion.sys-con.com/read/46789.htm">long been a fan</a> of the &#8220;magic&#8221; behind sites like Amazon, Flickr, and 30boxes. </p>
<p>So, after quite a bit of searching around in books and blogs, I managed to cobble together a couple of extremely simple scripts that take most of the mystique out of Ajax.  </p>
<p>In fact, we&#8217;re also taking the &#8220;x&#8221; (for XML) out of Ajax, since this routine works by having your page call a JavaScript function that passes a request to some server-side code which then returns pure HTML.  This HTML gets inserted into a container <code>div</code> on the calling page.</p>
<p>So here we go with the tutorial.  An Ajax &#8220;how-to&#8221; in three easy steps (you can also <a href="http://nealenssle.com/blog/files/simpleajax.zip">download the code</a>):</p>
<p>First things first, you need to get a &#8220;request object&#8221; that handles sending your request to the server.  So we need a JavaScript function (inside a <code>script</code> block):</p>
<pre>// initAjaxRequest():
//    Create a request object, based on browser type:

function initAjaxRequest() {
    var request;
    if (window.ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        request = new XMLHttpRequest();
    }
    return request;
}
</pre>
<p>Next, you&#8217;ll need to instantiate the request object at some point (this happens inside a JavaScript <code>script</code> block but outside of any function):</p>
<pre>// Set a variable to hold an Ajax request object:

var ajaxRequest = initAjaxRequest();
</pre>
<p>Finally, you&#8217;ll need a JavaScript function that you can call to actually send the request to the server.  The following function (inside a <code>script</code> block) takes URL parameter (that&#8217;s the server-side module, servlet, or page that will produce some HTML for us), along with a second parameter (&#8220;container&#8221;) that tells us where to put the resulting HTML:</p>
<pre>// sendAjaxGetRequest(url, container):
//    Send an asychronous request to a specific URL,
//    designating CSS container ID to hold the
//    response information (HTML).

function sendAjaxGetRequest(url, container) {
    ajaxRequest.open('GET', url);
    ajaxRequest.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded");
    ajaxRequest.onreadystatechange = function() {
        if (ajaxRequest.readyState == 4 &#038;&#038;
            ajaxRequest.status == 200) {
            document.getElementById(container).innerHTML =
                ajaxRequest.responseText;
        }
    }
    ajaxRequest.send(null);
}
</pre>
<p>Now, to actually use these JavaScript functions, all we need to do is:</p>
<p>1. Call the JavaScript <code>sendAjaxGetRequest(url, container)</code> function (perhaps via an &#8220;onclick&#8221; handler), specifying the URL of a page that &#8220;does something&#8221; on the server-side, and a &#8220;container&#8221;.  For example:</p>
<p><code>&lt;p onclick=&quot;sendAjaxGetRequest('doSomething.htm', 'responseDiv');&quot;&gt;Do something!&lt;/p&gt;</code></p>
<p>2. Make sure we have a &#8220;container&#8221; <code>div</code> on the calling page that will hold the resulting HTML.  For example:</p>
<p><code>&lt;div id=&quot;responseDiv&quot;&gt;&lt;/div&gt;</code></p>
<p>Note that &#8220;doing something&#8221; can be as simple as printing any HTML to the screen. For example, the &#8220;doSomething.htm&#8221; page could simply look like this:</p>
<p><code>&lt;p&gt;I did something!&lt;/p&gt;</code></p>
<p>Of course, this target page could be far more complex, such as a PHP page, ColdFusion template, or Java servlet that updates a database.  The point of Ajax is just that you&#8217;re now able to post a request to the server, do something, and get information back without having to refresh the page.</p>
<p>If you want to send form fields via a POST instead URL parameters via a GET, here&#8217;s a slightly different function:</p>
<pre>
function sendAjaxPostRequest(url, parameters, container) {
    ajaxRequest.open('POST', url);
    ajaxRequest.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded");
    ajaxRequest.onreadystatechange = function() {
        if (ajaxRequest.readyState == 4 &#038;&#038;
            ajaxRequest.status == 200) {
            document.getElementById(container).innerHTML =
                ajaxRequest.responseText;
        }
    }
    ajaxRequest.send(parameters);
}
</pre>
<p>This function takes a &#8220;parameters&#8221; argument, which can be an encoded string of form field parameters.  For example:</p>
<pre>
var url = "doSomething.php";
var parameters = "myField=" +
    encodeURI(document.myForm.myField.value);
sendAjaxPostRequest(url, parameters, "responseDiv");
</pre>
<p>That&#8217;s mostly it.  Enjoy!  (Again: You can <a href="http://nealenssle.com/blog/files/simpleajax.zip">download the code</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://nealenssle.com/blog/2006/09/26/simple-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

