<?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>Transcending Frontiers &#187; Keeping Context in Your AJAX Callbacks</title>
	<atom:link href="http://blog.thefrontiergroup.com.au/tag/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.thefrontiergroup.com.au</link>
	<description>Your peek inside the collective mind of The Frontier Group</description>
	<lastBuildDate>Tue, 03 Jan 2012 06:53:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Keeping Context in Your AJAX Callbacks</title>
		<link>http://blog.thefrontiergroup.com.au/2009/03/keeping-context-in-your-ajax-callbacks/</link>
		<comments>http://blog.thefrontiergroup.com.au/2009/03/keeping-context-in-your-ajax-callbacks/#comments</comments>
		<pubDate>Fri, 13 Mar 2009 08:19:04 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://thefrontiergroup.com.au/blog/?p=356</guid>
		<description><![CDATA[These days I&#8217;m using a lot of asynchronous calls to get data and dynamically build the UI on the client side. It generally allows a far nicer experience to be provided to the user, being able to update parts of the UI without reloading the whole page is one of the first steps to your [...]]]></description>
			<content:encoded><![CDATA[<p>These days I&#8217;m using a lot of asynchronous calls to get data and dynamically build the UI on the client side. It generally allows a far nicer experience to be provided to the user, being able to update parts of the UI without reloading the whole page is one of the first steps to your apps being able to wear a Web 2.0 moniker. </p>
<p>The general pattern for me these days has become : </p>
<pre class="javascript" name="code">
var callback = function CallBack(data) {
    ... Do Some Processing ....
}

var input_data = GatherData();
MakeRequest(target_url, data, callback);
</pre>
<p>I tend to use jQuery and so my callback is passed in the returned data from the target_url. My call back function then generally performs some tasks on the UI based on what it receives.</p>
<p>The problem though is that in this pattern you can&#8217;t get any data from the context when <code>MakeRequest()</code> is called into the scope of <code>CallBack</code>. It&#8217;s a scoping issue that falls outside of this little post, but if you&#8217;d like an explanation of how Javascript handles scope of variables then you can Google for Javascript scope chain or take a shortcut to <a href="http://www.digital-web.com/articles/scope_in_javascript/">this article</a>. Essentially when the call is made to <code>CallBack()</code> all it will have is it&#8217;s own variables and any globally accessible (window) variables. </p>
<p>This week though I had a thought and worked through it with one of my work mates, Tony. If you passed in a function that had the scope that included the context you wanted to pass, then maybe you&#8217;d be able to access whatever data from the callee you wanted. It turns out that this does work. </p>
<p>The way to do this is pretty simple, and I used it to create a simple function that would grab data and then populate a select element with options. In this case the context I&#8217;d like to keep is which select element is the target. </p>
<p>Say that I needed to run this over a bunch of select elements in quick succession then as the callbacks were issued they may end up out of the initial execution order, so the target element isn&#8217;t reliable if it&#8217;s been stored in a global variable. I could pass it in as a variable that would come back from the page that is returning the data but that just <a href="http://en.wikipedia.org/wiki/Code_smell">smells bad</a> to me. I think potentially JSONP is an alternative too, but this felt like the right way. </p>
<pre class="javascript" name="code">
$.getJSON(url, input_data,
	(function(target_element) {
		return function(response_data) {
			var html = [];

			for (var i = 0; i < response_data.length; i++) {
				item = response_data[i];

				html.push('
<option value="' + item['key'] + '">' + item['value'] + '</option>

');
			}

			target_element.children(':gt(0)').remove();
			target_element.append(html.join(''));
		};
	})(target_element)
);
</pre>
<p>Essentially the main thing that has changed is that we are now running an anonymous function at the time that the AJAX call is issued. This anonymous function itself returns a function that matches the signature that jQuery is expecting for the callback function. The scope in which this function runs contains the target_element because it was passed into the anonymous function as a parameter. I&#8217;m tempted to say that it&#8217;s all crazy Javascript scoping, but in reality it&#8217;s very cool and very powerful. </p>
<p>If you want to see the execution order of this then just put a some logging into the anonymous function and the callback function and you&#8217;ll see what I mean. It will probably make it easier to see what is going on too.</p>
<p>I&#8217;ve run into issues trying to get around these problems before and thankfully as mine and the team&#8217;s knowledge of Javascript increases I&#8217;m finding better and better solutions. I thought my previous method of approaching this problem was quite hacky but now I don&#8217;t feel so dirty. </p>
<p>Thanks to Tony too for working through this with me! </p>
<script src="http://feeds.feedburner.com/~s/TranscendingFrontiers?i=http://blog.thefrontiergroup.com.au/2009/03/keeping-context-in-your-ajax-callbacks/" type="text/javascript" charset="utf-8"></script>]]></content:encoded>
			<wfw:commentRss>http://blog.thefrontiergroup.com.au/2009/03/keeping-context-in-your-ajax-callbacks/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Always return a response to your Ajax requests</title>
		<link>http://blog.thefrontiergroup.com.au/2009/01/always-return-a-response-to-your-ajax-requests/</link>
		<comments>http://blog.thefrontiergroup.com.au/2009/01/always-return-a-response-to-your-ajax-requests/#comments</comments>
		<pubDate>Mon, 12 Jan 2009 02:20:11 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Inside TFG]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://thefrontiergroup.com.au/blog/?p=285</guid>
		<description><![CDATA[Ajax is a fairly broad technology with so many different client side and server side approaches that it&#8217;s hard to provide generic best practice rules. This however is one. Requests via ajax tend to be handled asynchronously these days, communicating with the server whilst keeping the user interface active and responsive. This approach provides a [...]]]></description>
			<content:encoded><![CDATA[<p>Ajax is a fairly broad technology with so many different client side and server side approaches that it&#8217;s hard to provide generic best practice rules. This however is one.</p>
<p>Requests via ajax tend to be handled asynchronously these days, communicating with the server whilst keeping the user interface active and responsive. This approach provides a potential problem though as it is possible to make a request and not worry about results, presuming what was sent just worked.</p>
<p>Better practice is to always respond from the server and at least have some form of simple logging at the client side so you can be certain communication is working as expected. It is simple for the server to respond with JSON in the form of:</p>
<pre name="code" class="javascript">{success:1}</pre>
<p>This provides several pieces of information. Firstly the server action completed and was not met with an error such as error 500 (server error) or error 404 (page not found). Also if we toggle the &#8220;success&#8221; value with true or false, depending on the success of the request, we know that the process we requested was successful or failed. In one small line we rule out several potential points of failure.</p>
<p>Note that most major JavaScript libraries provide a simple means of handling success and failure so this is not hard to implement. In the case of Prototype you need only look at the &#8220;onError&#8221; and &#8220;onSuccess&#8221; attributes when defining the initial Ajax request.</p>
<script src="http://feeds.feedburner.com/~s/TranscendingFrontiers?i=http://blog.thefrontiergroup.com.au/2009/01/always-return-a-response-to-your-ajax-requests/" type="text/javascript" charset="utf-8"></script>]]></content:encoded>
			<wfw:commentRss>http://blog.thefrontiergroup.com.au/2009/01/always-return-a-response-to-your-ajax-requests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handling Permissions for AJAX Requests</title>
		<link>http://blog.thefrontiergroup.com.au/2008/12/handling-permissions-for-ajax-requests/</link>
		<comments>http://blog.thefrontiergroup.com.au/2008/12/handling-permissions-for-ajax-requests/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 11:10:12 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://thefrontiergroup.com.au/blog/?p=248</guid>
		<description><![CDATA[Again I have a website where a lot of data transfer is done asynchronously and a large amount of the presentation is done using Javascript. Different users have different access to features across the site, and I can&#8217;t just rely on hiding links given the data is a simple HTTP request away. Protecting this data [...]]]></description>
			<content:encoded><![CDATA[<p>Again I have a website where a lot of data transfer is done asynchronously and a large amount of the presentation is done using Javascript. Different users have different access to features across the site, and I can&#8217;t just rely on hiding links given the data is a simple HTTP request away. Protecting this data on the server side has always been easy to me, but I&#8217;ve typically found building the persistent abstractions I like to have far more difficult on the client side. As per usual, it&#8217;s probably just another issue I haven&#8217;t spent enough time to get a grip on. </p>
<p>It&#8217;s possible technologies such as Prism and Gears will help with this in the future. Unfortunately, it is the present.</p>
<p>This time I think I have a solution that I&#8217;m pretty happy with though. On the server side it involves using the existing HTTP response codes to indicate to the requester what happened with their request. On the client side the <code>ajaxComplete()</code> event is used to handle these codes. </p>
<p>jQuery will automatically call the function you specify as your callback in an AJAX request if the request is successful, so I&#8217;m only interested in handling failures. At the moment I&#8217;m assuming that all of my calls use JSON for their data format, but the alternative is a case I can handle later if need be. Only do what is necessary right now is a great credo I think.</p>
<p>So here is my event handler, it&#8217;s very simple but the documentation on the arguments to the event are a little slight. The <code>success()</code> call just makes a call to the function specified in the original call, hence passing in an empty array, simulating no records returned. The code I&#8217;m handling is for 401: Unauthorized, which in this case is the truth. This code will be sent back when I determine that the user is trying to access some data they aren&#8217;t supposed to. <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP codes</a> handle the majority of cases you&#8217;ll run into.</p>
<pre name="code" class="javascript">
(function() {
	if (typeof(jQuery) != 'undefined') {
		jQuery().ajaxComplete(function(ev, req, settings) {
			if (req.status == 401) {
				settings.success([]);
				alert('You have insufficient privileges.');
			}
		});
	}
})();
</pre>
<p>The server side code is simple, it&#8217;s just a matter of sending back the appropriate <a href="http://php.net/header">header</a>:</p>
<pre name="code" class="php">
	header('HTTP/1.0 401 Insufficient Privileges', false, 401);
</pre>
<p>This function is specified in a global include where part of the website uses prototype, I&#8217;ve been slowly integrating jQuery. Therefore the first thing I do is check if jQuery has been defined, if it has then I register my function as the handler for the <code>ajaxComplete</code> event. Since it&#8217;s declared globally this will happen on every AJAX call. If the response code is 401 then first I pass back and empty array to my <code>success</code> handler so that the little loading notifier disappears, and then I notify the user of the error. </p>
<p>It seems to be a trend lately, but again this is just a very simple idea but I hope it saves someone some hassle. I know I&#8217;ve searched high and low on the topic and haven&#8217;t found a nice generic solution. </p>
<script src="http://feeds.feedburner.com/~s/TranscendingFrontiers?i=http://blog.thefrontiergroup.com.au/2008/12/handling-permissions-for-ajax-requests/" type="text/javascript" charset="utf-8"></script>]]></content:encoded>
			<wfw:commentRss>http://blog.thefrontiergroup.com.au/2008/12/handling-permissions-for-ajax-requests/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Dynamically Reducing Object Sizes in PHP</title>
		<link>http://blog.thefrontiergroup.com.au/2008/11/dynamically-reducing-object-sizes-in-php/</link>
		<comments>http://blog.thefrontiergroup.com.au/2008/11/dynamically-reducing-object-sizes-in-php/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 05:51:59 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Dynamic Languages]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thefrontiergroup.com.au/blog/?p=178</guid>
		<description><![CDATA[After using jQuery for quite a while I&#8217;ve become quite attached to using the power of callbacks when dealing with sets of data. I&#8217;ve seen equally and perhaps better abilities in Ruby but of course had been let down in the past by PHP&#8217;s lack of abilities as a dynamic language. Today I faced an [...]]]></description>
			<content:encoded><![CDATA[<p>After using jQuery for quite a while I&#8217;ve become quite attached to using the power of callbacks when dealing with sets of data. I&#8217;ve seen equally and perhaps better abilities in Ruby but of course had been let down in the past by PHP&#8217;s lack of abilities as a dynamic language.</p>
<p>Today I faced an issue due to the size of my objects. The problem essentially came down to the fact that for the largest objects such as Contact objects the amount of data passed back to the client when doing AJAX calls was pretty sizeable. I wanted to write a function that given a set of property names all the returning objects would be stripped of all but those properties.</p>
<p>I didn&#8217;t want to write a function for each set of properties I&#8217;d return, so I wrote a generic function that given an array of property names that was all that would be returned from that object and it was surprisingly easy and I think in the end highly dynamic and useful.</p>
<p>It uses the PHP array_walk() function which I&#8217;ve never used before. It&#8217;s a lot like the Array.each() methods that many other languages have.</p>
<pre class="php" name="code">	private function GetContacts() {
		$filter = RequestQuerystring('filter');
		$properties = RequestAll('properties');

		if (isset($properties)) {
			$properties = explode(',', $properties);
		}

		if (isset($filter)) {
			$contacts = [large_objects]
		}

		if (isset($contacts) &amp;&amp; is_array($properties)) {
			array_walk($contacts, 'mod_ajax::FilterObjects', $properties);
		}

		echo json_encode($contacts);

	}

	private static function FilterObjects(&amp;$object, $key, $properties) {
		foreach (get_object_vars($object) as $k =&gt; $v) {
			if (!in_array($k, $properties)) {
				unset($object-&gt;$k);
			}
		}
	}</pre>
<p>Basically for this array of large objects on each one we call FilterObjects. That has to be a function or static method which I learned as I went. The object is passed in by reference so that any change made to it is reflected in the original array, and it just goes through the variables (properties) of the object and kills anything that isn&#8217;t in the allowable parameter list.</p>
<p>This allows me to trim large objects dynamically for any of my client side calls for data and I think is definitely going to save me time in the future. I remember when I first started using PHP I wrote a function for each object to spit out XML, then I progressed to JSON, now I&#8217;ve got a nice filter method.</p>
<p>I still feel like there must be a better way to do things, but quite possibly that would exist in another language.</p>
<script src="http://feeds.feedburner.com/~s/TranscendingFrontiers?i=http://blog.thefrontiergroup.com.au/2008/11/dynamically-reducing-object-sizes-in-php/" type="text/javascript" charset="utf-8"></script>]]></content:encoded>
			<wfw:commentRss>http://blog.thefrontiergroup.com.au/2008/11/dynamically-reducing-object-sizes-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using jQuery For Webpage Notifications</title>
		<link>http://blog.thefrontiergroup.com.au/2008/10/using-jquery-for-webpage-notifications/</link>
		<comments>http://blog.thefrontiergroup.com.au/2008/10/using-jquery-for-webpage-notifications/#comments</comments>
		<pubDate>Sat, 18 Oct 2008 04:47:10 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Websites or Tools]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Growl]]></category>
		<category><![CDATA[jGrowl]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Notifications]]></category>

		<guid isPermaLink="false">http://thefrontiergroup.com.au/blog/?p=71</guid>
		<description><![CDATA[With the prevalence of AJAX and background operations on the web these days it pays to have an unobtrusive method for notifying the user when certain things happen. Typically thise is done with an animated graphic, or a popup but these usually mean you have to make a choice between relaying information and being intrusive, [...]]]></description>
			<content:encoded><![CDATA[<p>With the prevalence of AJAX and background operations on the web these days it pays to have an unobtrusive method for notifying the user when certain things happen. Typically thise is done with an animated graphic, or a popup but these usually mean you have to make a choice between relaying information and being intrusive, or being minimal with information and being very passive.</p>
<p><a href="http://growl.info/">Growl</a> is an application that has become quite popular on the Mac, it allows applications to popup a notification sticky in the corner of the screen for a while. They&#8217;re very handy and unobtrusive and now someone has gone ahead and implemented a similar notification style using <a href="http://jquery.com/">jQuery</a>. He calls it <a href="http://stanlemon.net/projects/jgrowl.html">jGrowl</a> which makes sense.</p>
<p>I think I&#8217;ll be using it quite a bit in a few projects I&#8217;ve been working on recently. It seems like the best of both worlds and very easy to implement now that someone else has done the heavy lifting for me.</p>
<script src="http://feeds.feedburner.com/~s/TranscendingFrontiers?i=http://blog.thefrontiergroup.com.au/2008/10/using-jquery-for-webpage-notifications/" type="text/javascript" charset="utf-8"></script>]]></content:encoded>
			<wfw:commentRss>http://blog.thefrontiergroup.com.au/2008/10/using-jquery-for-webpage-notifications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>20 Great AJAX Tools and Effects</title>
		<link>http://blog.thefrontiergroup.com.au/2008/10/20-great-ajax-tools-and-effects/</link>
		<comments>http://blog.thefrontiergroup.com.au/2008/10/20-great-ajax-tools-and-effects/#comments</comments>
		<pubDate>Wed, 08 Oct 2008 01:47:03 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Websites or Tools]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://thefrontiergroup.com.au/blog/?p=62</guid>
		<description><![CDATA[While the term AJAX may possibly be a little overhyped and overused these days, when AJAX is used appropriately it can really enhance the usability of an application and make many tasks far quicker to complete than they otherwise would have been. One of the first examples of this would be auto-completing search fields but [...]]]></description>
			<content:encoded><![CDATA[<p>While the term AJAX may possibly be a little overhyped and overused these days, when AJAX is used appropriately it can really enhance the usability of an application and make many tasks far quicker to complete than they otherwise would have been. One of the first examples of this would be auto-completing search fields but for anyone using Facebook, Flickr or any number of <em>Web 2.0</em> applications they probably forget how tedious some of the things they do now used to be.</p>
<p>This list of <a href="http://nettuts.com/web-roundups/20-excellent-ajax-effects-you-should-know/">20 great AJAX effects</a> has many of the effects you&#8217;ll see on the larger sites that are truly embracing AJAX such as better form validation, auto-completing text box lists and file uploading. If you&#8217;re looking to create a truly awesome experience for your user on your websites you really need to be implementing these UI patterns in your websites now!</p>
<script src="http://feeds.feedburner.com/~s/TranscendingFrontiers?i=http://blog.thefrontiergroup.com.au/2008/10/20-great-ajax-tools-and-effects/" type="text/javascript" charset="utf-8"></script>]]></content:encoded>
			<wfw:commentRss>http://blog.thefrontiergroup.com.au/2008/10/20-great-ajax-tools-and-effects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

