The Frontier Group - Blog

Keeping Context in Your AJAX Callbacks

March 13th, 2009, by aaron

These days I’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.

The general pattern for me these days has become :

var callback = function CallBack(data) {
    ... Do Some Processing ....
}

var input_data = GatherData();
MakeRequest(target_url, data, callback);

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.

The problem though is that in this pattern you can’t get any data from the context when MakeRequest() is called into the scope of CallBack. It’s a scoping issue that falls outside of this little post, but if you’d like an explanation of how Javascript handles scope of variables then you can Google for Javascript scope chain or take a shortcut to this article. Essentially when the call is made to CallBack() all it will have is it’s own variables and any globally accessible (window) variables.

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’d be able to access whatever data from the callee you wanted. It turns out that this does work.

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’d like to keep is which select element is the target.

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’t reliable if it’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 smells bad to me. I think potentially JSONP is an alternative too, but this felt like the right way.

$.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('');
			}

			target_element.children(':gt(0)').remove();
			target_element.append(html.join(''));
		};
	})(target_element)
);

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’m tempted to say that it’s all crazy Javascript scoping, but in reality it’s very cool and very powerful.

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’ll see what I mean. It will probably make it easier to see what is going on too.

I’ve run into issues trying to get around these problems before and thankfully as mine and the team’s knowledge of Javascript increases I’m finding better and better solutions. I thought my previous method of approaching this problem was quite hacky but now I don’t feel so dirty.

Thanks to Tony too for working through this with me!

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


Always return a response to your Ajax requests

January 12th, 2009, by tony

Ajax is a fairly broad technology with so many different client side and server side approaches that it’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 potential problem though as it is possible to make a request and not worry about results, presuming what was sent just worked.

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:

{success:1}

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 “success” 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.

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 “onError” and “onSuccess” attributes when defining the initial Ajax request.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


Handling Permissions for AJAX Requests

December 17th, 2008, by aaron

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’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’ve typically found building the persistent abstractions I like to have far more difficult on the client side. As per usual, it’s probably just another issue I haven’t spent enough time to get a grip on.

It’s possible technologies such as Prism and Gears will help with this in the future. Unfortunately, it is the present.

This time I think I have a solution that I’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 ajaxComplete() event is used to handle these codes.

jQuery will automatically call the function you specify as your callback in an AJAX request if the request is successful, so I’m only interested in handling failures. At the moment I’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.

So here is my event handler, it’s very simple but the documentation on the arguments to the event are a little slight. The success() 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’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’t supposed to. HTTP codes handle the majority of cases you’ll run into.

(function() {
	if (typeof(jQuery) != 'undefined') {
		jQuery().ajaxComplete(function(ev, req, settings) {
			if (req.status == 401) {
				settings.success([]);
				alert('You have insufficient privileges.');
			}
		});
	}
})();

The server side code is simple, it’s just a matter of sending back the appropriate header:

	header('HTTP/1.0 401 Insufficient Privileges', false, 401);

This function is specified in a global include where part of the website uses prototype, I’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 ajaxComplete event. Since it’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 success handler so that the little loading notifier disappears, and then I notify the user of the error.

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’ve searched high and low on the topic and haven’t found a nice generic solution.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


Dynamically Reducing Object Sizes in PHP

November 19th, 2008, by aaron

After using jQuery for quite a while I’ve become quite attached to using the power of callbacks when dealing with sets of data. I’ve seen equally and perhaps better abilities in Ruby but of course had been let down in the past by PHP’s lack of abilities as a dynamic language.

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.

I didn’t want to write a function for each set of properties I’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.

It uses the PHP array_walk() function which I’ve never used before. It’s a lot like the Array.each() methods that many other languages have.

	private function GetContacts() {
		$filter = RequestQuerystring('filter');
		$properties = RequestAll('properties');

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

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

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

		echo json_encode($contacts);

	}

	private static function FilterObjects(&$object, $key, $properties) {
		foreach (get_object_vars($object) as $k => $v) {
			if (!in_array($k, $properties)) {
				unset($object->$k);
			}
		}
	}

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’t in the allowable parameter list.

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’ve got a nice filter method.

I still feel like there must be a better way to do things, but quite possibly that would exist in another language.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


Using jQuery For Webpage Notifications

October 18th, 2008, by aaron

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.

Growl 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’re very handy and unobtrusive and now someone has gone ahead and implemented a similar notification style using jQuery. He calls it jGrowl which makes sense.

I think I’ll be using it quite a bit in a few projects I’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.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


Follow Us

Stay in the Loop

  • Enter your email address to subscribe to our mailing list. You'll get updates about our products, specials and bonus offers, and general behind the scenes news from our team.

Twitter

Newsletters

Alexa Rank

Testimonial

The boys at The Frontier Group are amazing! For such a relaxed and personable organisation, they have phenomenal technical ability and a rampant professionalism. They have customisable solutions for all of my IT needs and they always deliver, on time and beyond expectation.

They fix problems other service providers can't and they helped me get a critical section of my web site up and running 10 minutes after I emailed the request!

Alex Hyndman, Nexus Car Share.

Featured Project

Case Study - Caudo Group - www.caudo.com.au

Website

www.caudo.com.au

Caudo Machinery

Caudo Group engaged our services to redesign their outdated website. We sent our photographer on-site to capture the essence of their business and turned it into a stunning web design.