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.

Where did the Brilliant Indian Minds Go?

There was an interesting question during the last Intro Session for Unlimited Power. One of the participants who attended was surprised when Kirtanya listed out the methodology of the course. She mentioned NLP, Transactional Analysis, Silva Mind control and Life-Skills as ways to tap into the Unlimited Power each one of us has within us. He was stunned to see that none of the Indian sciences were listed and was curious to know if we (Indians) did not discover anything at all in the mind power arena.

The truth is, in the ancient days there was no parallel to the Indian Sciences when it came to addressing the human mind and life. Just think about it, we had everything, a nice climate, riches, wealth, forests, rivers; we were just too bountiful. On the other hand the western hemisphere at the same time was caught up in a turmoil of wars, harsh climates; their energy was so much focused on surviving the extreme weather. The Indians having no challenges to conquer in the external world turned their entire attention inward. The mind and consciousness and human life became very interesting research subjects for them.

And so there was an outpouring of greatest of works on the science of mind itself. The yoga sutras of Patanjali, The Vedas, Vedanta, Brahma sutras, Upanishads, Yogavasishta, every one of these is a miracle even to read through. In fact, it is said that the Mahabharatha is an ultimate thesis on the various human personalities and it contains 72000 characters each representing a personality type. So India had no dearth for wisdom. Some of its treasures still stay on.

However, the same cannot be said of the modern day India. Over a century now we have been harping on the past glories. With the advent of the British rule and subsequent poverty we have become increasingly preoccupied in solving the external challenges and are oblivious to the internal ones. The roles are in a sense reversing between the west and the east. With its high levels of sophistication, pleasure in the external world, and breaking families they are increasingly searching inward for answers and so research into the human mind has picked up momentum. With technological edge they are precisely able to study the human brain itself and so are paving way for some of the greatest discoveries in human history itself.

It is actually a pity that when technology is at its peak, the brilliant Indian minds are preoccupied with selfish miseries. In the modern era we seldom shine in our ancestor’s strong forte, our inborn talent – the mind. Of course there are the modern Gurus who teach on the mind but more often than not they are mouthed words than a direct personal discovery or an experience and always tainted with a religious bias. The need of the hour is brilliant young Indian minds dedicated to unraveling the mysteries of the human mind-brain organ. The aptitude for this is in our very genes. The result of such dedication will be mind boggling discoveries that will help the human species itself cross the last frontier – the mind.

Waiting for that day!

Toon: When Sensex plunged …

Keat, my friend, is quite spiritual. An ardent meditator with experience for almost 14 years. She keeps telling me about mystical experiences. I believe in mindfulness and awareness. Sometimes my comments invalidate these experiences. Recently when sensex (Indian stock market index) plunged and some of my money was caught in it, she made use of the opportunity to portray me this way.

The man in orange is me(Ganesh). The girl in the toon is keat. And with us is Parthi (man in blue). We form a trio.

Sensex Plunges

Ganesh and God – Keat’s Toons

A friend of mine keeps posting these cartoons about me. Her cartoons tickled me no end coz, she had this uncanny knack of catching my serious moments as well as the not so serious ones into comical strips that brought a fond smile or a hearty laugh. I felt like sharing them with my reader friends. Hope you enjoy them too as much as I did. I will keep posting these toons as and when they come.

I am a die-hard non-vegetarian, especially fond of chicken. While my friend is a strict vegetarian. Amazed at my ability to eat chicken, she put this toon.

Ganesh and God

Groovy: Private is not private

If I have to name one language that I thoroughly enjoy programming in, it has got to be Groovy. I work with it almost on a daily basis although the platform for my day job doesn’t require it. Personally, I love groovy for the obvious reasons and also for the not so obvious reason – It has some sentimental value to me since I have been following this language since its inception.

That said, one of the things that surprised me while using groovy was its Private modifier. It seems groovy completely ignores its mere presence. I am used to the unavailability of privates in javascript for a pretty long time and so I religiously follow naming conventions to separate private from public assets. I have never used similar naming conventions for groovy because I thought the concept of private existed. Unfortunately, I was wrong. Let us dive into a few short examples to see what I mean…

class User {
   String firstName;
}

def user = new User()
user.firstName = "John"
println user.firstName

This is a typical POGO. firstName is private by default. Public Setters and Getters are generated automatically at compile time. When the caller uses this property, he will actually be using the public Setter or Getter instead of directly accessing the field. Typical groovy stuff…

On the flip side, if you don’t want groovy to generate the Getters and Setters at compile time, then you should modify the field using a private keyword as shown in the snippet below.

class User {
   private String firstName;
}

def user = new User()
user.firstName = "John"
println user.firstName

Now, groovy won’t generate the Getters and Setters for firstName. But if you run the above code, you will be surprised to see that the field is still accessible. The caller is able to set and get the firstName.

I thought maybe groovy is probably not suppressing the Getter and Setter generation due to some bug and that is the reason why this field is still accessible. But that is not the case, as you can see in the next example. In this snippet, you can see that I use groovy’s “.@” syntax to access the field directly and the field is still accessible.

class User {
   private String firstName;
}

def user = new User()
user.@firstName = "John"
println user.@firstName

Then I tried private methods. No surprise there, since I got used to the surprise by now. Yes, the private methods are also directly accessible.

class User {
   private String firstName;
   private String name() {
      firstName;
   }
}

def user = new User()
user.@firstName = "John"
println user.name()

Thank god though. There was some silver lining. Java classes aren’t able to access all of these private fields, properties and methods. It is only the other groovy scripts that are able to access it. The example below will demonstrate the same.

class User {
   private String firstName;
}

class UserTest {
   public static void main(String args[]) {
      User user = new User();
      System.out.println(user.firstName); // compile error
      System.out.println(user.getFirstName()); // compile error
      System.out.println(user.name()); // compile error
   }
}

After some googling, I found a few jira issues here, here and here.

After going through these links, it looks like this was a bug in groovy from the beginning, but nobody bothered to fix it because for such a dynamically and reflectively capable language private is just a documentation anyways.

Groovy – Syntax sugar for map keys

Groovy keeps putting a smile on my face again and again. This time it is for a cool syntax sugar that i found useful as well as clean. Lets get to the chase without too much of chit-chat.

Let’s create a Map of people and their ages in groovy using literal syntax. You could write it this way…

Map people = [
   "John" : 24,
   "Steve" : 30,
   "Cathy" : 25 
];

Pretty straight-forward! But don’t you think the double quote around each name looks like unnecessary clutter. I thought so and I guess groovy developers thought so too. So, they made it easy on us and allowed us to just ignore the quotes. So, the same map can be written as shown below, without the quotes and groovy still understands what you mean. In this case, groovy considers the key to be of String data type. If you used numeric literals for keys, groovy would consider them as their appropriate numeric type.

Map people = [
   John : 24,
   Steve : 30,
   Cathy : 25 
];

You may ask that this is well and good, but then how will i use my variables as keys? It so happens that many a times when we create a map using literal syntax we use only string literals or numeric literals as keys and not a variable reference. So, this syntax covers for most of the cases. But, if you definitely need to use your variables as keys, then you have two options.

The first option is to not use literal syntax. Instead you could just use normal map.put() syntax to get the job done. But this doesn’t look groovy.

Map people;
people.put(name1, 24)
people.put(name2, 30)
people.put(name3, 25)

The second option is to wrap the keys with parenthesis as shown below. This way you are explicitly telling groovy to consider them as variable references.

Map people = [
   (name1) : 24,
   (name2) : 30,
   (name3) : 25 
];

Ok, now this syntax is more cluttered than the original one with quotes wrapped around them. I agree. But, considering the frequency with which this is going to be used, I think this is a better alternative.

Groovy – Add Static & Instance methods dynamically

Like Ruby and other dynamic languages in its Genre, groovy also allows us to add methods to a class dynamically at runtime. You need not restrict yourself to adding instance methods alone. Even static methods are supported.

To showcase this, let’s create a class called User with name and email properties.

class User {
  String name, email
}

Now, let’s add a static newInstance() method to create a new instance of this class. Technically speaking this is not a method; it is a closure. This example is contrived, but I hope you get the idea.

User.metaClass.static.newInstance = {name, email ->
  new User(name: name, email: email)
}

Now, let’s add an instance method to update the “name” property of User. Here, the “delegate” references the “this” pointer. Remember, this is not a method; it is a closure.

User.metaClass.updateName = { name ->
  delegate.name = name
}

The very next line you can start creating a new instance of user using this dynamically added static method and instance method as shown below.

User user = User.newInstance('ganesh', 'g@e.com')
assert 'ganesh' == user.name

user.updateName ("ganeshji")
assert "ganeshji" == user.name

It is not necessary that you add these new methods right below the class. You can add it anywhere in your code. As long as you call these methods after the lines that define these new methods are executed you should be fine.

The Nboomi Experience

NboomiI am glad I could finally get back to blogging after a long period of hibernation. Almost an year back, me and three of my friends founded Triomatrix Webservices Private Limited, an ambitious company aimed at creating web-based services to innovatively automate businesses in India. Fanatically caught in the clutches of this marathon venture I almost forgot about everything else in life except for the ravishing beauty of our first product – www.nboomi.com.

Nboomi.com is an innovative real-estate portal from Triomatrix that literally translates the dreams of home-shoppers around the globe into a living reality. At its core, Nboomi creates a virtual world that allows home-shoppers to walk inside and experience their future home in all its splendor with just a computer and an internet connection. Being a virtual world, walking around the home is just the tip of the iceberg. Beyond that, you can paint walls, tile floors, texture doors and windows, create and organize furniture and much more, all inside your favorite web browser. You are limited only by your imagination.

Very recently, we took a beta of Nboomi into the wild to field test it and I can distinctly see the attention it is attracting. At present we have successfully completed the technical component and are handing it over to the business team to take care of the sales and marketing activities. I am confident that with the right nurture and a bit of luck, Nboomi can take the real-estate field by storm.