I Can’t Believe It’s Not XMLHttpRequest!

Posted in technology, Work with tags , , , , , , , , on March 2, 2008 by klayhamn

As if my initial amazement of the simplicity of ajax was not enough, as part of my job at Outbrain I have recently come across an even simpler (and in some ways, better) method to implement asynchronous client-side requests to the server. In fact, it is SO simple you would be tempted to use it even when you don’t really need it!

First, I must clarify and say that this other method does not really come to replace the “traditional” AJAX path (involving the use of the native javascript ‘XMLHttpRequest’ object), but simply poses an alternative which might better suit some specific cases. I barely found any refrences to this method on the net. The few places which mentioned it, called it: “Dynamic Script Loading”. Therefore, since this is essentially “uncharted territory”, I shall allow myself to give it a more appropriate name myself, one which would also allude to its purpose. I call it: “Dynamic Pseudo-Script Request” or DPSR.

DPSR is basically a utilization of an old JS feature of browsers: The ability to dynamically create a script element on the client-side at runtime. Since <script> elements support external URLs (as their ‘src’ attribute), this opens the door to an endless world of possibilities. <script> elements have the benefit of being able to initiate requests to ANY server as well as executing the response (as long as it conforms to the syntax of javascript, and to be on the safe-side – as long as the content-type is: “text/javascript”). If we could “cheat” the element into running server-side code (which isn’t really a JS file), we could perform any action we want – asynchronously (with parameters in the URL), and even have the ability to dynamically handle the response, if we choose to. The browser doesn’t “care” what happens when it initiates the request, it only cares about the response (of which we have total control).

For example, take the following scenario: We have an online store (http://example.mystore.com), which allows users to add items to their ‘shopping cart’. Now, naturally, we wouldn’t want an action like this (which involves sending data to the server) to have any disruptive effect on the user’s experience. We don’t want to take him anywhere, we don’t want to submit any forms. We just want a simple “call” to be made: http://example.mystore.com/addItem?id=766118. Now, for the sake of this example – let’s assume that this store is insanely popular, and that it’s entirely possible for an item to be sold-out in the time-frame between its presentation to the user – and the user’s action. Also, let’s assume there’s a limit to the number of items any user can purchase.

If we want the user to feel comfortable (and be able to cope with this insane shopping spree), we should allow him to “seamlessly” add items to his cart without affecting anything else on his browser – except for the result of the action itself. This is where DPSR comes in.

<script type=”text/javascript”>

function callBackFunc(status) {

switch(status) {

case 1: break;

case 2:alert(‘item sold-out!’);break;

case 3:alert(‘shopping cart full’);break;

}

}

function addItemToCart(id) {

var newSE = document.createElement(“script”);

newSE.src=”http://example.mystore.com/addItem?id=&#8221; + id +”&method=callBackFunc”;

document.body.appendChild(newSE);

}

</script>

<body>

. . .

<a href=”javascript:void(0)” onclick=”addItemToCart(766118)”>Add to shopping cart</a>

. . .

</body>

What happens here is that when we add an item, a script element is planted on the page, with a URL that runs some server-side code. This code returns a javascript response : ” callBackFunc( … ); “. Because the browser was expecting javascript and we gave it what it wants, it would kindfully execute it for us. Simple but ingenious. Granted, this code could be made much more elegant. We could make sure that script elements replace each other rather than be added one after the other ad infinitum; we could make a more user-friendly handler for the result; etc…

The main advantages of XMLHttpRequest over DPSR is support for HTTP headers (when things go wrong and we get 500, 503, 404, etc.), out-of-the-box support for XML responses, the ability to make POST requests, and all the benefits of having a fully functional JS object. DPSR, however, enables a straightforward approach that is cross-domain , cross-browser, and is more light-weight. It’s simple to integrate in your application, and since it’s not an object, we can easily return ANY callback function we want, which gives us a great deal of flexibility.

The main drawback of XMLHttpRequest, in my eyes, is that the flow that results is less intuitive to comprehend and manage. For example, we cannot easily manipulate the VIEW (i.e the page from which we initiated the call) after the response arrives, without hard-coding this behavior into the callback handler. This is not only inflexible, but also creates a dependency between the AJAX logic and the view layer. For example, if we have a re-usable piece of DHTML – such as a registration form, we don’t want our ajax function to “know” about the page we placed that form in. Instead, we want each page to be able to have a different implementation of the callback function, and we want to be able to TELL the server what’s the name of the callback function we want it to use (and wrap the result in).

The main drawback of DPSR, I think, is that it forces you to manipulate the DOM. This, however, is obviously very easy to work around.

Feature
XMLHttpRequest
DPSR
HTTP Status
Supported
Not Supported
Cross-Domain
Requires server-side workaround
Supported
Cross-Browser
Requires browser sniffing
Supported
Callback Functionality
Supported; flow is confusing; unflexible
Supported; simple flow; flexible
XML Response
Supported
Requires Handling
POST method
Supported Not Supported
Tidyness Clean Messy (DOM manipulation)

Generally speaking, I think it would be safe to say that XMLHttpRequest is better suited for data retreival, while DPSR serves as an excellent solution for data manipulation (and for very simple calls, such as nickname-availability checks in registration forms).

Higher Education; or – The Road Not Taken

Posted in Life with tags , , , , , , on February 28, 2008 by klayhamn

Yes, it has been a while since I wrote anything. I’ve been a bit busy with work lately and in the weekends I felt pretty lazy. I have long since discovered that when something is avoided – even if only for a short while – it becomes increasingly more difficult to deal with or get back to, over time. This is why I always try to set little deadlines for myself. Of course, this doesn’t always work.

And now for some news: I received the results of my application to “Shenkar” (the Israeli design school) – which were negative. It was partially an attempt to prove (to myself?) that I can get accepted without putting too much effort into my portfolio. Well, I was wrong, and this amusing little gamble may turn out to be one of the most influential events in my life as of yet, since its consequences have already changed my (academic) future considerably.

Since I am 99% certain that I would get accepted to Tel-Aviv University (I applied to a dual program consisting of Computer Science and East-Asia Studies), that leaves me whith an interesting dilemma, different than the one I thought I’d have to deal with. Either I wait another year, for the chance that I would get accepted to “Shenkar”, or I start now with something else. As I see it now, it shifts the balance towards the TAU path, but obviously I still have a lot of thought to put into this before I can decide.

Graphic Design – Is that what I want to do? Is that what I should do? Would I enjoy it more? Or less? Am I willing to wait another year just for the chance? Am I willing to spend 4 years studying it instead of 3? Am I willing to devote 90% of my time for this? Would I regret it half-way through? Would it get me a satisfying job? Would I earn enough money in that job? Am I better off pursuing this as a hobby rather than a career or an academic goal?

A lot of questions I really don’t know the answer to at this stage. In fact, I probably never will. Whatever I decide – would end up being a gamble. I can just hope it would be as calculated a gamble as I can make it.

And here’s one of my favorite poems, which happens to be very relevant to the issue at hand:

The Road Not Taken /Robert Frost (1916)

Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;

Then took the other, as just as fair,
And having perhaps the better claim,
Because it was grassy and wanted wear
Though as for that the passing there
Had worn them really about the same,

And both that morning equally lay
In leaves no step had trodden black.
Oh, I kept the first for another day!
Yet knowing how way leads on to way,
I doubted if I should ever come back.

I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I—
I took the one less traveled by,
And that has made all the difference.

The Weekly Review #2 – Aspects of Time Travel

Posted in Humor, philosophy with tags , , , , , , on February 3, 2008 by klayhamn

As promised, here is another sizzling report from the Weekly Review series. In this episode, I will look into everyone’s favorite plot-device: Time Travel! Since I was 5 years old I dreamed of constructing my own time machine. I don’t know why I found it so fascinating so early in my life, but I suppose that I always thought of the same-old Arrow of Time to be slightly constricting and boring. Now I know it also means that sooner or later I would meet my inevitable doom, but that’s not the issue. There’s no doubt about it – time travel captivates our hearts and dreams. It’s simple, it’s powerful – and it’s probably never gonna happen. Still, here’s a funny review to read while you come to terms with your mortal fate.

Grandfather Paradox – The funny thing about paradoxes is that even though we’ve known about them for thousands of years (when Greece actually mattered to anyone), we are still not exactly sure how they should be handled – so we try our best to avoid them. And I’m not talking about those : “this sentence is a lie” type of paradoxes. I’m talking about those incidents where reality contradicts itself in a way that makes you feel uncomfortable. For all we know, these things could lead to anything from ridicule and confusion – to the utter destruction the universe. Naturally, paradoxes play an integral part in time travel, since virtually any trip to the past could create one. A “Grandfather Paradox” is what happens when you travel back in time, kill your grandfather (doing so now would have no interesting effects) and thus prevent your own birth, and as a result – also prevent the murder of your grandfather, allowing you to be born, only to come back and stab him in the back again like a relentless grand-son-of-a-bitch… etc., etc. I guess they are called “Grandfather Paradoxes” because no one wants to find out that he failed to undo existence – simply because he didn’t know who his real dad was. Better play it safe and aim for the elderly.

Sports Almanac – I always wondered what’s the true purpose of Sports Almanacs (for those who don’t know, almanacs are: “annual publications containing tabular information in a particular field or fields”). Well, it seems that time travel would just not be the same without them. They provide us with a way to get rich quickly, impress people with our knowledge or even prove to be life-savers in those nasty cases of toilet emergency (which, as it turns out, can be caused by frequent trips in the 4th dimension).

Arriving in the Nude – For some inexplicable reason, time travel is often depicted as a journey that rids you of your clothes. What may have started as just an excuse to film Arnold Schwarzenegger’s butt – turned into the de-facto standard. I suppose the scientific basis for this must have something to do with the String Theory. In any case, I can already see how this property could be exploited by the adult-entertainment industry and lead to a whole new genre of time-travel porn, with titles such as: “Donna and Goliath”, “Debby Does The Renaissance” and “Jenna Screws With History”.

Altering Histroy – What’s cool about time is that the further you travel backwards in it, the less you need to do to change it. In order to alter all the events of the 20th century, for example, it would be enough to for you to pay a short visit to the stone age and stomp on some guy’s foot. You come back and to your surprise – suddenly everyone talks Chinese; eating Gefilte Fish is all the rage; and Al-Qaeda is a popular Canadian sitcom.

Variety of Methods – It’s good that we have so many ways to travel to the past. Cars, machines, wormholes… My personal favorite is Physical Impact. One hit to the head and bam! you’re in 1997, making people think you’re weird when you roll your eyes as they play Green Day’s “Good Riddance” for the first time ever on the radio. Anyway, I still think there is room for some more time-travel related gizmo’s. My ideas so far include: “Time Toilet” (“Why not dump your excess load – on the unsuspecting faces of the legends of old? Now for only $999.99″), “Time Refrigerator” (“Keep your foods frozen… IN TIME!”) and “Time Wrist-watch” (“Be able to tell… the TIME!”).

Lost is BACK!

Posted in Life, TV with tags , , on February 1, 2008 by klayhamn

***SPOILER WARNING!***
One of my favorite shows of all times is finally back for another season. The third season’s unexpected finale left us shocked to discover the future of (some) of the survivors:

This scene really sent shivers down my spine. The moment Kate appeared I said to myself: “Conspiracy Theory?”, and then immediately realized I am watching a post-island scene. Jack shouting : “We have to go back!” with such emotional intensity (and good acting, I should add) had a huge effect on me. I didn’t so much care WHY he wants to go back – only that it must be a really STRANGE reason that is related with the island’s mystery.
So now the story continues. My father says that it’s never going to have any real resolution. That there won’t be any logical explanation and most of the big questions would remain unanswered. Personally, I don’t think so, especially now that the show has been given a dead-line (2010), and a finite number of episodes left to go (47). However, I did come to discover two paranoias that I have acquired, and which I believe are worthy of being universally recognized:

  • The Fear that Actors Who Play Pivotal Characters in a TV Series You Love, Would Find Their Untimely Demise Before the Proper End of the Show and
  • The Fear that YOU Yourself Would Have your Life Ended Or Otherwise Turned Incapable of Witnessing The Rest (and especially the end) of the Story

Now, perhaps counter intuitively – it is the former that is the worst of the two. This because, if you die you probably would have LESS to worry about, whereas if Matthew Fox (who plays Doctor Jack Shephard) died, you would still be around to live a miserable life that is devoid of peace or quiet. You would wonder for all eternity what it could have been like if the story would have continued as it should have.
Is it just me? In case not, then I wonder what it says about us as humans in this day and age. We let these shows become such an integral part of our lives, have such great influence on us. We are inspired by them, we are moved by them. We feel sad, happy or excited. I think (good) television is in some way a (good?) substitute for the lives we cannot live. We can’t really go and crash ourselves on a mysterious deserted island. Well, we can but we’d probably die of the impact or the malaria. As much as I respect the role books play in our society, I think it’s time we recognize that their time is passed, and now is the time of fully-sensual entertainment. Who knows, maybe in the not-too-distant future we could even touch Kate through the screen… Whoops, sorry, my mind was wandering there for a second.

Addiction to Endings

Posted in Life, TV with tags , , , , , on January 21, 2008 by klayhamn

Well, I just finished watching “That’s 70’s Show” series finale.
That 70’s Show
Even though the last season sucked (mostly because of the absence of TWO of the main characters – Kelso and Eric), the ending was nice. This is truly one of the best comedies that were ever made. I don’t know if it’s the funniest, but I doubt there is any other show with such lovable and memorable characters, and actors with such amazing chemistry between them. Also, it gives you a taste of what it might have been like to be a teenager in the 70’s. At the risk of sounding corny, I’d say that besides the obvious “groovy” aspects of the decade, it also seems to have been the time of simpler, better days (yet without the nativity that is usually associated with the “classic” 50’s for example).

Anyway, the final episode also reminded me again of how much I like endings, especially sad ones that involve goodbyes. Well, to be honest, in my personal life I usually hate goodbyes and try to avoid them as much as I can. I simply find those situations awkward. But when it comes to other people (or TV), I just love to see people part ways. For example, one time I was watching this series of lecture videos I found on the net. They were taken in an actual algebra class in some American university, which means the lectures actually spanned across a whole semester. Call me weird, but I really felt moved by the teacher’s closing words in the last lecture he gave.

I guess endings and goodbyes remind us of how transient our lives are. Like it isn’t enough that our life is short in itself, we have to go through its separate “acts”: Just when we get familiar with our surroundings and the people we meet, we are forced to leave everything behind and move on, usually with nothing more than the memories we collected. But I guess this the way of life – If we stayed in the same place forever, and nothing ever changed, it’d be pretty boring. We might even get sick of the people around us. By flowing with the wind of change, we get to keep fond memories of the past, and have something to look forward to in our future.

Simple Physics

Posted in Humor with tags , , , , , , on January 18, 2008 by klayhamn

There are several things that amaze me in this random photo I found on the net:
brewhouse_brouhaha_sm.jpg
One of them, is that the guy seems almost indifferent to the the rather unusual (and unexpected?) event that takes place just in front of his face. The woman, on the other hand, seems bummed, startled and embarrassed – all the the same time. Maybe it’s because women are more open about their emotions. Or maybe it’s just because she has threatening amounts of glass-shards and beer particles coming her way.

The Weekly Review #1

Posted in Humor, Life with tags , , , on January 14, 2008 by klayhamn

Very few things in life that are intentionally funny actually manage to make me laugh out loud. (I’m not sure why that is, but I know it isn’t because I lack a good sense of humor. In fact, back in my army unit I was categorized as the “funny guy”, and oftentimes I’d find myself trapped in never ending laughing sessions with my co-workers). The only the two that I can actually name are: the Book of Ratings (which sadly has not been updated for a long time), and the Reasons to Hate Star Wars guide. Coincidentally – both of them are reviews of familiar aspects in our life!

Inspired by the first example, I decided to attempt to create a similar feature in my own blog – which would be called: “The Weekly Review”. Disclaimer: I am not necessarily as amusing in writing as I am in real life, and therefore I take no responsibility if you end up feeling sad, cheated or confused by the following content!

Ways to Cook Food:

Fire – While clearly the most primitive of all methods, it’s still the most reliable one. It helps the third-world and the LOST characters survive, and had the honor of assisting our homosapien ancestors to evolve from crazy monkeys to the iPod-geared TV-addicted earth-polluting lazy bums we are today. Also, it’s the only method whose “OFF switch” is usually carefully-directed, mutually-synchronized male pee.

Toaster – toasters seem to have a lot going for them, especially considering the fact they can only cook ONE type of food. For over 100 years they have been impressing us with their ability to move our bread around (albeit not significantly), and helped some of us commit suicide in an amusing way. Also, this device is the only one of the group which can be controlled over the internet, an excellent property of home-appliances that in 30 or so years from now, we could probably not live without!

Microwave – By far, the coolest of the thermal instruments, but it comes with a dire price. Like a heavenly gift from a mischievous Greek God – it offers men the key to a world of efficiency and success, as long as they obey one simple rule: tempting though it may be, a mortal must NEVER place any metal inside the box! So, sure, it would re-heat those yummy leftovers from Tuesday – but if you dare break the ancient law, all hell is bound to break lose.

BBQ – Grills are often associated with outgoing attitudes, social-interaction, national holidays and freak accidents. Somehow everything tastes better when it’s grilled. Even cheese. In fact, this is the reason they started making BBQ-FLAVORED foods. Which makes me wonder: what is exactly that elusive BBQ essence which those snacks claim to have captured? Coal? Smoke? Or perhaps the care-free happiness of a weekend shared with close friends…?

Boiling – I always believed a clear distinction should be made between The Four Elements of the earth. A simple logical deduction can lead us to astonishing conclusions: Water negates fire, and therefore has no place in the world of high-temperature consumption! It just doesn’t work. The mere fact that boiled chicken takes on a pale color reminiscent of old peoples’ skin, should be enough of a warning sign for all of us.

Room - Granted, this isn’t a “cooking method” in the conservative sense of the word. I have to hand it to Room though, for having just the right temperature in order to thaw our frozen foods, as long as we’re patient enough.

Follow

Get every new post delivered to your Inbox.