<?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>Reflections &#187; Programming</title>
	<atom:link href="http://reflections.irythia.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://reflections.irythia.com</link>
	<description>The ramblings and ravings of a ... what?</description>
	<lastBuildDate>Sat, 01 Jan 2011 06:40:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>GPC Version 2: Phoenix Rising</title>
		<link>http://reflections.irythia.com/2010/12/31/gpc-version-2-phoenix-rising/</link>
		<comments>http://reflections.irythia.com/2010/12/31/gpc-version-2-phoenix-rising/#comments</comments>
		<pubDate>Sat, 01 Jan 2011 01:09:18 +0000</pubDate>
		<dc:creator>Illianthe</dc:creator>
				<category><![CDATA[Gaming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Game Prototype Challenge]]></category>
		<category><![CDATA[Phoenix Rising]]></category>

		<guid isPermaLink="false">http://reflections.irythia.com/?p=336</guid>
		<description><![CDATA[I wanted to write this post right after the submission deadline earlier last week, but I put it off due to a case of not feeling well (technical term). So instead, this shall be my last piece for the year! Hopefully I&#8217;ll be writing a little more frequently in the following months, with university and [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to write this post right after the submission deadline earlier last week, but I put it off due to a case of <em>not feeling well</em> (technical term). So instead, this shall be my last piece for the year! Hopefully I&#8217;ll be writing a little more frequently in the following months, with university and a whole bunch of projects coming up. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Background</strong></p>
<p><a href="http://studios.irythia.com/games/phoenixrising/">Phoenix Rising</a> is a JavaScript/HTML5-based puzzle game that I wrote for the second iteration of the <a href="http://gameprototypechallenge.com/">Game Prototype Challenge</a>, a week-long game jam. Organized by former colleague Jason Kaplan, the purpose of the challenge was to motivate game developers. And motivate me it did; I saw it as a good opportunity to try my hand at game development. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>Idea</strong></p>
<p>This was my <em>first ever</em> attempt at writing a game, so I wanted to keep things simple. Basically, this meant that I couldn&#8217;t do anything that required complex mechanics. I was also working that week and had a couple of events to attend so time was definitely an issue.</p>
<p>I chose to write the game in JavaScript, making use of the canvas element introduced in the HTML5 specifications. There are a couple of reasons for this. One: I&#8217;m already quite experienced when it comes to web development so I wanted to take full advantage of that knowledge. Two: I haven&#8217;t actually worked with canvas before even though I&#8217;ve seen all sorts of cool demos that others have written. This was a good way for me to get my feet wet on both fronts.</p>
<p>It took me a few hours to come up with a workable concept once the themes for the challenge (immortality and thin ice) were announced (I was actually up &#8217;till 4 AM thinking while reading up on basic game development). One of the first things that came to mind was the notion of cracking tiles that would deteriorate into holes once you&#8217;ve stepped on it a couple of times; a set of such tiles would essentially be a puzzle that has to be navigated carefully. This was one of the mini-obstacles in <em>Golden Sun</em>, a RPG that I hold in the highest regards. In the end, it turns out that I would do something similar &#8211; a set of ice tiles that melt into a trail of impassible water. I wasn&#8217;t entirely sure how to fit immortality in at first (early ideas included obtaining an elixir of life, spiritual ascendancy, etc.), but then it hit me. Why not do something featuring one of my favourite creatures of all time, the phoenix? Everything came into place once I wrapped my head around that thought, including the melting ice (a phoenix <em>is</em> made of fire after all), the collection of twigs to build a nest, the mini-story&#8230;</p>
<p><strong>Development</strong></p>
<p>Although I fleshed out the game concept fairly early in the week, I didn&#8217;t actually start coding seriously until Thursday. In hindsight I should have started sooner, but there was a lot of material for me to read up first (as stated, I haven&#8217;t done game development before). JavaScript is pretty quirky as a language too which didn&#8217;t help much (I typically use jQuery syntax for the things that I need in the average web development project).</p>
<p>I started with a simple game loop using setInterval() that is first called when the DOM is ready. For this particular project, a continuous game loop was probably overkill; something based on player input would have been far more efficient. I wanted the flexibility though, in case I felt like implementing AI for enemies and whatnot. It turns out this was a rather bad decision as I overestimated the performance of JavaScript in certain browsers; FF 3.6 was quite laggy although FF 4 and Chrome 8 ran the game alright.</p>
<p>All of the level data is stored in separate XML files which are parsed into game objects as needed. This allowed me the flexibility of adding new levels on-the-fly as well as giving an easy way for others to create their own custom maps (in the future?). The jQuery framework makes the parsing process painless, only requiring an AJAX request and a callback function. I&#8217;m actually pretty sure it&#8217;s standard practice to store this data separately, although it was more out of intuition for me.</p>
<p>It turns out that drawing on the HTML5 canvas is rather simple, though you are more-or-less limited to primitive objects. I made extensive use of drawImage() since most of what I had was stored externally. The visual part of the game consists of a bunch of images hastily drawn using my trusty Wacom Bamboo tablet. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  It was actually slightly challenging drawing things that would tile correctly (mainly the wall) and writing code to display the right image wasn&#8217;t a walk in the park either. I probably messed up here; there was likely a <em>much</em> better way of doing things (i.e. not having separate cases for everything).</p>
<p>Everything else is rather straightforward; I used a 2-dimensional array to store the current game state and had various checks in place for &#8220;special&#8221; events. Arkayle&#8217;s abilities were actually a last minute add-on that I felt added a lot more depth to the game (I knew something similar had to be added eventually &#8211; there is only so much you can do with a puzzle where you couldn&#8217;t normally retrace your steps). Unfortunately since I was crunched for time, I couldn&#8217;t really do too much level design. The result is a three-level game where only the last level is slightly challenging. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p><strong>Lessons Learned</strong></p>
<p>There were a few major issues that I ran into. I found that drawing on the canvas is pretty damn slow especially when the dimensions are large (e.g. 1000px x 500px). Especially for a game like this, it was probably a much better idea to redraw when something actually happened (e.g. player input), rather than at a constant interval. An alternative would have been to not use canvas: DOM manipulation is another path that I could have taken.</p>
<p>A second major issue that I found was when I was trying to import my &#8220;art&#8221; assets into the game. There is an issue with drawImage() which tries to render an image onto the canvas even if it hasn&#8217;t been loaded yet. I&#8217;m not sure if this is a bug or by design (if it <em>is</em> by design, I&#8217;d like to know why). One of the ways to resolve this issue was to use drawImage() on image load:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> img <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Image<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
img.<span style="color: #000066;">onLoad</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    canvasContext.<span style="color: #660066;">drawImage</span><span style="color: #009900;">&#40;</span>img<span style="color: #339933;">,</span> xStartingCoordinates<span style="color: #339933;">,</span> yStartingCoordinates<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
img.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;path/to/image.png&quot;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Unfortunately, this caused a whole bunch of flickering due to my game loop (at least in Firefox 3.6) so I opted to preload all of my images instead.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> images <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;image1.png&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;image2.png&quot;</span><span style="color: #339933;">,</span> ...<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> img <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> images.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        img<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Image<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        img<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> images<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Turns out that this works quite well. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  The smart way of dealing with so many images (20 at my last count) would have been to use sprite maps to minimize the number of HTTP requests, but I didn&#8217;t want to deal with the hassle at the time (as mentioned, crunch period!).</p>
<p>There were a few more kinks along the way (e.g. dealing with JavaScript&#8217;s prototypical &#8211; rather than classical &#8211; inheritance), but they were pretty minor. My code base is pretty messy, though that was to be expected writing something I didn&#8217;t know how to write, using tools that I didn&#8217;t know how to use. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  In hindsight, I should have introduced a lot more separation between the engine and game logic. I also should have found a way to reuse code more effectively (see the Entity object). As for the game itself, I should have added in a few more abilities for Arkayle to use, as well as more levels (right now it doesn&#8217;t seem much like a game). Ah well&#8230;</p>
<p>All in all, I had a great time working on this prototype. I felt like I learned a lot from the process and I hope to apply that in future projects. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://reflections.irythia.com/2010/12/31/gpc-version-2-phoenix-rising/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Building a Web Scraper Using JavaScript and jQuery</title>
		<link>http://reflections.irythia.com/2010/01/25/building-a-web-scraper-using-javascript-and-jquery/</link>
		<comments>http://reflections.irythia.com/2010/01/25/building-a-web-scraper-using-javascript-and-jquery/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 08:38:43 +0000</pubDate>
		<dc:creator>Illianthe</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Web Scraping]]></category>
		<category><![CDATA[YQL]]></category>

		<guid isPermaLink="false">http://reflections.irythia.com/?p=211</guid>
		<description><![CDATA[When building web applications, sometimes there&#8217;s a need to fetch data from other sources. Perhaps you&#8217;re building a custom RSS feed of news items based on your interests or you want to aggregate data from several sites. In any case, it&#8217;s not always possible to do this elegantly; you may not have direct access to [...]]]></description>
			<content:encoded><![CDATA[<p>When building web applications, sometimes there&#8217;s a need to fetch data from other sources. Perhaps you&#8217;re building a custom RSS feed of news items based on your interests or you want to aggregate data from several sites. In any case, it&#8217;s not always possible to do this elegantly; you may not have direct access to the raw data and an existing API may not exist. For these situations there&#8217;s one general (albeit fragile) solution: manually parse the end result when a page is loaded in a browser.</p>
<p>There are many different ways to build a web scraper. A server-side language such as PHP will have a much easier time as there are less limitations and existing libraries (such as cURL) to accomplish the task. I&#8217;ll be using JavaScript (with the jQuery library), however, as I want a standalone client independent of server technology.</p>
<p>Let&#8217;s start with a random snippet of code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> fetchPage<span style="color: #009900;">&#40;</span>url<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    $.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
        type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;GET&quot;</span><span style="color: #339933;">,</span>
        url<span style="color: #339933;">:</span> url<span style="color: #339933;">,</span>
        error<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>request<span style="color: #339933;">,</span> <span style="color: #000066;">status</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Error fetching '</span> <span style="color: #339933;">+</span> url<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            parse<span style="color: #009900;">&#40;</span>data.<span style="color: #660066;">responseText</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The above function attempts to make an AJAX call to a specified web page, fetch the HTML of said page and pass it to a parsing function. Simple enough, right?</p>
<p>Unfortunately there&#8217;s a little problem with this. Client-side programming languages have to deal with something called the <a href="http://en.wikipedia.org/wiki/Same_origin_policy">same origin policy</a> which basically restricts scripts from accessing external domains. From a security standpoint this is obviously a good thing; however it can be a headache for web app. developers (indeed, there are ideas such as the origin HTTP header to solve this). (The following bit can be ignored if the scraper is on the same domain as the data source &#8211; but in such a case why is said scraper even necessary?)</p>
<p>In this case, there are a couple of solutions (that I can think of). Both of them take advantage of the fact that JavaScript can read <a href="http://en.wikipedia.org/wiki/Json">JSON</a> even if it is located on a different domain.</p>
<ul style="text-align: left;">
<li>The first one is writing a complementary server-side script that takes a few arguments (such as the target URL), makes the call, parses the result into JSON format and passes it back to the calling function. It&#8217;s a simple idea, but I never really liked it because it introduced a major dependency (which, in my case, can be a pain to deal with). However, it&#8217;s definitely a viable solution which works extremely well.</li>
<li>The second is using an existing system such as Yahoo&#8217;s YQL to fetch the required data and return it in a structured form. This is the method that I&#8217;ll be using.</li>
</ul>
<p>YQL is an interesting little beast. From <a href="http://developer.yahoo.com/yql/">their site</a>:</p>
<blockquote><p>The Yahoo! Query Language is an expressive SQL-like language that lets you query, filter, and join data across Web services. With YQL, apps run faster with fewer lines of code and a smaller network footprint.</p></blockquote>
<p>I haven&#8217;t had too much time to look into it so I do what all programmers do: Google the living crap out of a problem to find a solution. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  In this case, <a href="http://www.wait-till-i.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/">Chris Heilmann has a great post</a> on how to load external content via. various methods including YQL. To simplify things, James Padolsey <a href="http://github.com/jamespadolsey/jQuery-Plugins/tree/master/cross-domain-ajax/">wrote a plugin</a> that detects an external AJAX call and passes it to YQL automatically.</p>
<p>Anyway, that solves the problem of fetching data from an external source. All that&#8217;s left is extracting the relevant pieces for whatever application is being built. Consider the following example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> parse<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;h1&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">text</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The parse() function takes the responseText data from the earlier fetchPage() function and then proceeds to pick at it slowly and painfully. What&#8217;s really cool about it is that pretty much all of jQuery&#8217;s selectors can be used to select relevant data. In the above case, I&#8217;m trying to extract text inside the first &lt;h1&gt; tag found on a page and outputting it as an alert to the browser. Obviously there are more complex uses for this but they are outside the scope of this post. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>And&#8230;that&#8217;s it! <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  Those two code blocks combined pretty much handles all of the grunt-work in extracting data from external sources. Again, this is a rather fragile solution &#8211; it can break if the target page&#8217;s HTML changes (one possible solution is to pick unique identifiers or classes). In addition, some sites may have restrictions on their data &#8211; but I&#8217;m sure everyone reads those <a href="http://en.wikipedia.org/wiki/Terms_of_service">long-winded documents</a>. <img src='http://www.irythia.com/portal/reflections/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://reflections.irythia.com/2010/01/25/building-a-web-scraper-using-javascript-and-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The &#8220;A&#8221; in &#8220;AJAX&#8221;</title>
		<link>http://reflections.irythia.com/2010/01/16/the-a-in-ajax/</link>
		<comments>http://reflections.irythia.com/2010/01/16/the-a-in-ajax/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 00:49:39 +0000</pubDate>
		<dc:creator>Illianthe</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://reflections.irythia.com/?p=201</guid>
		<description><![CDATA[Consider the following code snippet using JavaScript (with the jQuery library): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 function blah&#40;&#41; &#123; var pagedata; $.ajax&#40;&#123; type: &#34;GET&#34;, url: &#34;test.php&#34;, error: function&#40;request, error&#41; &#123; alert&#40;&#34;Error: &#34; + error&#41;; &#125;, success: function&#40;data&#41; &#123; pagedata = data; &#125; &#125;&#41;; return pagedata; &#125; [...]]]></description>
			<content:encoded><![CDATA[<p>Consider the following code snippet using JavaScript (with the jQuery library):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> blah<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> pagedata<span style="color: #339933;">;</span>
    $.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
        type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;GET&quot;</span><span style="color: #339933;">,</span>
        url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;test.php&quot;</span><span style="color: #339933;">,</span>
        error<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>request<span style="color: #339933;">,</span> error<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Error: &quot;</span> <span style="color: #339933;">+</span> error<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            pagedata <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> pagedata<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Looks reasonable enough. The purpose of the function is to make a GET request to some page (&#8220;test.php&#8221; in this case), store the result in a temporary variable and return said variable (of type string).</p>
<p>However, it turns out that this doesn&#8217;t work too well. When the function is called, chances are pretty good that the returned string is empty. Why? At first I thought it was because of some weird variable scoping rules in JavaScript, but that didn&#8217;t really make too much sense.</p>
<p>It turns out that I forgot about the &#8220;A&#8221; in &#8220;AJAX&#8221; (i.e. <strong>Asynchronous</strong> JavaScript and XML). The function above doesn&#8217;t execute in a top-bottom manner; the $.ajax() call is made in parallel with the rest of the script. Generally this isn&#8217;t too much of a problem (indeed, it&#8217;s a valued property by those making web applications) but in this case it isn&#8217;t what I want.</p>
<p>Anyway, there&#8217;s a simple solution to this. What I want to do is make the call synchronous with the rest of the script. Fortunately, jQuery makes this extremely easy in the $.ajax() method by providing an option (async: false) to turn this off. Thus:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> blah<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> pagedata<span style="color: #339933;">;</span>
    $.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
        async<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">,</span>
        type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;GET&quot;</span><span style="color: #339933;">,</span>
        url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;test.php&quot;</span><span style="color: #339933;">,</span>
        error<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>request<span style="color: #339933;">,</span> error<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Error: &quot;</span> <span style="color: #339933;">+</span> error<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            pagedata <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> pagedata<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This locks up the browser while the call is being made so it&#8217;s probably not the best solution. It shouldn&#8217;t matter too much with small requests though (or requests made with the user&#8217;s consent via. the UI or something).</p>
]]></content:encoded>
			<wfw:commentRss>http://reflections.irythia.com/2010/01/16/the-a-in-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

