Is it an AJAX Request or a Normal Request?

In modern web application development, many a times you would want to know if the incoming HTTP Request is an AJAX request or just a Normal request. Have you come across this requirement? I have, and the solution that I found turned out to be pretty straight-forward and I will be sharing it with you here.

Whenever an AJAX request is sent to the server, a special header named X-Requested-With with a value of XMLHttpRequest is attached to the request. So, a simple check to see whether the X-Requested-With header has a value of XMLHttpRequest solves the challenge. An example will give you more clarity. Take a look at the examples of isAjax() methods in two famous server-side programming languages – Java and PHP.

Java:

public static boolean isAjax(request) {
   return "XMLHttpRequest"
             .equals(request.getHeader("X-Requested-With"));
}

PHP:

function isAjax() {
   return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
              && 
            ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}

From the code above, it should be clear that if the method returns true, then you received an AJAX request. If the method returns false, you received a Normal HTTP Request.

Now you know how to find out if it is an AJAX request or not. But how is it useful? What do you do with it?

Have you heard of the term Unobtrusive javascript. Come on, It is a buzzword these days. There is a lot to writing Unobtrusive javascript code, but one of its features – Progressive Enhancement – stands out from the rest. Again, let me explain this with an example.

Let us assume that you have designed a beautiful looking web page with tabbed navigation. Being a hard-core AJAX fan and an efficiency aficionado you don’t like to bring back a full page with the headers and the footers and the sidebars when your user clicks on a Tab. Instead you would love to bring back only the content area for the tab via AJAX and innerHTML it into its respective place. Correct? The good programmer inside you has also told that you should not hard-code the URL for the AJAX call in your javascript. Instead, your tab should be designed as an anchor whose href attribute points to the URL for the content. So far so good? Now, when the user clicks on the Tab, you collect the URL from its href attribute and fire an AJAX call to the server. The server obediently accepts the request and sends back the content just for the active tab.

<ul>
   <li><a href="/tab1.page" rel="#tab1">Tab 1</a></li>
   <li><a href="/tab2.page" rel="#tab2">Tab 2</a></li>
   <li><a href="/tab3.page" rel="#tab3">Tab 3</a></li>
</ul>

<div>
   <div id="tab1">Content for Tab1</div>
   <div id="tab2"> Content for Tab2 </div>
   <div id="tab3"> Content for Tab3 </div>
</div>

You would like to believe that all is well and good… Unfortuntately this is where the challenge of Progressive Enhancement begins. How do you plan to support browsers with JavaScript disabled. Yes, there are quite a few people who still do that for the fear of script related worms. How do you plan to support automated bots? Don’t you want the Google bots and the Yahoo bots to index all your pages with full content? Do you know what these users will see? They will see a half-baked page with just the active tab’s content and no styles – not even the header, footer or the sidebar. I am sure you don’t want this to happen. That is when the isAjax() method comes useful.

Whatever you did on the client side – HTML, CSS and javascript – is great and perfect. You separated the behavior from style and markup. So, you don’t have to touch it. You just need to do a small bit of work on the server-side.

In our case, when JavaScript is disabled, the browser will take over and execute its default behaviour of firing a Normal request to the URL specified in the href attribute. When JavaScript is enabled, JavaScript will take over and will fire an AJAX request to the same URL. In both cases the same server-side resource (like in Java or PHP) will receive the request. Now that you have decided to support Progressive Enhancement, you will have to check if the incoming request is an AJAX request or a Normal request using the isAjax() method shown earlier. In case of an AJAX request, you will send back only the content area of the tab thereby providing an efficient version of your application to JavaScript enabled users. In case of a Normal request, you will send back an entire page including the tab’s content, thereby providing a less efficient yet fully functional version of your application to JavaScript disabled users.

// Pseudo Code
if(isAjax(request) {
   return "Content area for the tab";
} else {
   return "Full page including tab content";
}

Now you can feel proud that you are not one of those who just talk about Unobtrusive JavaScript but you are one of those who have implemented it. I sincerely hope this article was useful. Feel free to drop in a comment with suggestions and/or feedback.

Update 1:

Based on the input provided by a buddy called Sabob from dzone, X-Requested-With is set only by AJAX libraries like jQuery, Mootools, Prototype etc. If you are coding AJAX by hand, then you will have to explicitly set this header while sending a request. More importantly you should somehow abstract it using good OO principles so that you don’t have to explicitly code this line every time you send an AJAX request.

Ctrl + Key Combination – Simple Jquery Plugin

In a recent web application I was working on, I had a need for the “Ctrl + S” hotkey to save an entry to the database. Being a an avid jquery fan, I immediately searched the plugin repository for any plugin that fits the bill. I was not very surprised to find a very comprehensive jshotkeys plugin. It was feature rich and addressed all the requirements for hotkeys in a jquery powered application and obviously my requirement was fulfilled as well.

But the basic issue (and advantage too) with any plugin is that it is written for a wide range of audience. So, although my requirement was only for a “Ctrl + key” combination, I had to part with my bandwidth for all other features this plugin offered. Like my famous jCarouselLite plugin, I like my javascript code kept to the minimum. So, I decided and wrote a short yet sweet plugin that would solve only the problem I have at hand. Unsurprisingly, the plugin code turned out to be only 195 bytes (minified). Given below is the code for the same…

$.ctrl = function(key, callback, args) {
    var isCtrl = false;
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null
        
        if(e.ctrlKey) isCtrl = true;
        if(e.keyCode == key.charCodeAt(0) && isCtrl) {
            callback.apply(this, args);
            return false;
        }
    }).keyup(function(e) {
        if(e.ctrlKey) isCtrl = false;
    });        
};

This is how it works:

1. You want to execute a function when the user presses a “Ctrl + key” combination.
2. You as a developer should call the plugin method and pass in 3 parameters.
3. 1st Param: The “key” user should press while he is pressing Ctrl.
4. 2nd Param: The callback function to be executed when the user presses “Ctrl + key”.
5. 3rd Param: An optional array of arguments, that will be passed to the callback function.

In the code given below, when the user presses the “Ctrl + S” key combination, the anonymous callback function passed in as the second parameter is called.

$.ctrl('S', function() {
    alert("Saved");
});

Here, when the user presses the “Ctrl + S” key combination, the anonymous callback function passed in as the second parameter is called with the arguments passed in as the third parameter.

$.ctrl('D', function(s) {
    alert(s);
}, ["Control D pressed"]);

Thats it. I feel it is simple yet effective and solves a common requirement in modern web applications.

What do you think?

Update

A comment provided by “A Nony Mouse” in this blog entry clarified that, we don’t have to store a boolean called “isCtrl” to check if the “Ctrl” key is down while another key is being pressed. It is enough to check for e.ctrlKey as it will return true if the “Ctrl” key is down even if another key is being pressed along with Ctrl. Based on that input the “Ctrl + Key” plugin has been updated. Take a look at the updated code below. For archiving purposes, I am leaving the original version of the code above without any changes.

$.ctrl = function(key, callback, args) {
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null 
        if(e.keyCode == key.charCodeAt(0) && e.ctrlKey) {
            callback.apply(this, args);
            return false;
        }
    });        
};

JQuery: Waiting for Multiple Animations to Complete

Have you ever come across a situation where you wanted to execute a certain piece of code after an animation has completed running? This is a very common use-case in modern web development. jQuery team knows it, and that is why they accept a callback function as argument for every kind of animation call. In the example below, we pass in a callback function that will be executed after the “slideDown” animation is complete. This is the usual scenario.

$("#animateMe").slideDown(function() {
	// This piece of code will be executed 
	// after the animation is complete
});

But, in many other scenarios you might want to wait for multiple animations to complete before executing a certain piece of code. Lets assume that the two elements – “#element1” and “#element2” – are currently getting animated. Our goal is to execute a piece of code after both elements are finished with their respective animations. This is where it gets tricky. I was facing one such challenge today. The solution I have arrived at is to use the “:animated” pseudo-selector and “setInterval” to repeatedly check and wait until the animations have completed running. An example will clarify what I mean

var wait = setInterval(function() {
	if( !$("#element1, #element2").is(":animated") ) {
		clearInterval(wait);
		// This piece of code will be executed
		// after element1 and element2 is complete.
	}
}, 200);

In the example above, I use “setInterval” to repeatedly check if these two elements are NOT being “:animated”. If this condition is not met, then it means that atleast one of them is still getting animated. So, “setInterval” will check for the same condition again in 200 ms until the condition is met. If the condition is met, it means that the animations are complete. So, I immediately do a “clearInterval” and stop checking for this condition again. Any code written after this statement will get executed after both the animations are complete.

Ofcourse, the same code can be modified for more than two elements as well. Some more work, and we can make it handle any number of elements. But, I was wondering if there was an easier, better and more efficient approach to solve the same challenge. If fellow jquery lovers are aware of such solutions please feel free to leave a comment.