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.


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.


json_decode() Not Working in PHP?

November 7th, 2008, by aaron

This took me a few minutes today to work out and find an answer on Google so I thought I’d share it.

I had a string that I was posting from a form and while Firebug on the client said that the string was valid, on the server side PHP’s json_decode() function was returning me a NULL indicating invalid JSON. I spit out the string using good old var_dump() and I could see straight away that I would need to strip some slashes from it, but I couldn’t figure out why.

I don’t like to simply know how to fix something, I like to know why it was broken in the first place! A bit of Googling gave me the answer, it turned out to be because of the magic_quotes setting in PHP.

Instead of just wrapping everything in a stripslashes() call I decided to write a wrapper function that will take into account whether magic_quotes is on or off. It will also allow me to do whatever I want later one if I wanted to parse a particular type of data or something.

Here is the code. As you can see it’s nothing fancy, but it works and hopefully it saves people some time.

function _json_decode($string) {
	if (get_magic_quotes_gpc()) {
		$string = stripslashes($string);
	}

	return json_decode($string);
}

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.