jQuery 1.1.3: Speed Improvements and Bug Fixes

After a long wait, jQuery 1.1.3 has been released! (Download it at the jQuery site) When I first adopted jQuery a year ago, the library boasted both faster speeds and smaller size than any other JavaScript Ajax/DOM tool. With the release of jQuery’s version 1.1.2, a number of jQuery’s operations became very slow and inefficiencient, as evidenced by MooTool’s SlickSpeed CSS Selector Test (found via Ajaxian) which crept up a few weeks ago.

This new release boasts an 800% speed improvement with a number of its selectors along with various enhancements across the board! The selector speed boost makes me one happy camper. Check out the enhancements as it compares to 1.1.2:

Browser jQuery 1.1.2 jQuery 1.1.3 % Improvement
IE 6 4890ms 661ms 740%
Firefox 2 5629ms 567ms 993%
Safari 2 3575ms 475ms 753%
Opera 9.1 3196ms 326ms 980%
Average improvement: 867%

And here’s how it now stacks up against the SlickSpeed test:

Browser Prototype jQuery Mootools Ext Dojo
IE 6 1476ms 661ms 1238ms 672ms 738ms
Firefox 2 219ms 567ms 220ms 951ms 440ms
Safari 2 1568ms 475ms 909ms 417ms 527ms
Opera 9.1 220ms 326ms 217ms 296ms 220ms

In addition to the speed enhancements, there were several other notable things:

  • Unicode Selectors: Yup…now you can use fancy non-english characters.
  • Escape Selectors: This is awesome. Now, if you use weird characters (i.e. punctuation) in a class/id name, you can now escape those characters within the selector syntax. E.g. $(“div#foo\.bar”)
  • Inequality Selector: You can now select elements where their attributes do not match a specific string of characters. E.g. $(“div[@id!=test]”)
  • :nth-child() improvements: jQuery has supported selectors like :nth-child(1) and :nth-child(odd) since the beginning of jQuery, now they’ve added advanced :nth-child selectors, such as:
    • $(“div:nth-child(2n)”)
    • $(“div:nth-child(2n+1)”)
    • $(“div:nth-child(n)”)
  • Space-separated attributes: After being removed in jQuery 1.0, this selector has now been brought back by popular demand. It allows you to locate individual items in a space-separated attribute (such as a class or rel attribute). E.g. $(“a[@rel~=test]”)
  • Animation Improvements: Animations are now significantly faster and smoother. Additionally, you can run more simultaneous animations without incurring any speed hits.
  • DOM Event Listeners: Internally, the jQuery Event system has been overhauled to use the DOM Event system, rather than the classical “onclick” style of binding event handlers. This improvement allows you to be more unobtrusive in your use of the library (not affecting the flow of other libraries around it). Additionally, it helped to resolve some of the outstanding issues that existed with binding event listeners to IFrames.
  • Event Normalization: Some great steps have been taken to normalize keyboard and mouse events. You can now access the event.which property to get most details about the specific key or button that was pressed.
  • Multiple .is(): The .is() method can now take multiple selectors, separated by a comma. This allows you to test your jQuery set against multiple selectors. E.g. $(“div”).is(“:visible, :first”)
  • Browser Version: A commonly requested feature, by plugin authors, was a way to determine what browser version their users were using. We now expose an extra property through which this information can be accessed. E.g. jQuery.browser.version

Additionally, the jQuery team has addressed 80+ bugs and has roadmapped out the next two releases (v1.1.4 and v1.2). To check out the full jQuery 1.2 roadmap, go here.

Coda – Finally A Mac Development Tool I Like

Coda I’ve had a Mac for quite a while now (well…I have two and hopefully a third very soon) and sadly development tools on the Mac have been pretty lame. I began development in a Windows environment a number of years ago and grew very happy (and spoiled) with EditPlus. The features that I found myself using within that editor that I am unable to live without are:

  • Single Window Environment
  • Custom Syntax Highlighting
  • Regular Expression Find/Replace
  • Function/Method List
  • Native FTP/SFTP
  • Intuitive Remote Site Browsing
  • Remote File Reload
  • Preview Tool

My attempts at finding Mac development software that suited all those needs have turned up pretty lame results. For the past year I’ve been suffering with BBEdit. While it is a fairly decent editor, its FTP support and multi-window interface just left me wanting something more.

Enter the newly released Coda.

This is the diamond in the rough! It provides everything that EditPlus had and a bunch more, integrating Panic‘s Transmit FTP application; a Terminal window; a sexy Editor with all the features I love; a browser window (Safari); a CSS Editor (which I’ll never use, although it’s cool); and a development Book library. Wow. Awesome stuff. Or as Panic puts it:

Text editor + Transmit + CSS editor + Terminal + Books + More = Whoah.

introducing coda. grow beautiful code.

Not only is their editor a beautiful application, their website is definitely something to write home about. Stunning. What’s even cooler is the fact that because I bought a Transmit license a few months back, I received a discount when I bought my Coda license. w00t! So…if you find yourself still on the hunt for a Mac Development Tool…Coda is the answer. Heck, even if you have one you like…Coda is better :)

JavaScript Shell

While at The Ajax Experience I noticed a tool that a few of the speakers made use of that was missing from my arsenal. The tool? JavaScript Shell.

This little beauty, once you’ve added the bookmark to your browser allows you to open a JavaScript Shell for any page you happen to be on! The shell lets you enter JavaScript from command-line to manipulate the page, trigger functions, analyze properties, etc. All libraries that the site has loaded are available within the Shell…so, if you use jQuery or some other toolkit, all defined functions and plugins are usable.

Here’s some features and pre-defined functions from the JavaScript Shell site

Features

  • You can enter statements and expressions at the same prompt.
  • The result of each non-void statement or expression is shown.
  • User-defined variables.
    • b = document.body
  • User-defined functions.
    • function f() { return 5; }
  • JavaScript error messages are shown in red.
  • Previous statements and expressions are available through Up and Down arrow keys.
  • Tab completion.
  • Multiline input (Shift+Enter to insert a line break).
  • If the shell is opened using a bookmarklet, JavaScript typed into the shell runs in the context of the original window.
  • Works well in Firefox, mostly works in Opera 8 and in IE 6 for Windows.

Built-in functions

  • ans: the result of the previous expression.
  • print(expr): prints expr on its own line.
    • for(i = 0; i < 6; ++i) print(i * i)
  • pr(expr): prints and returns its input, so you can use it to print intermediate results in the middle of an expression.
    • function fact(n) { return n>0 ? pr(n*fact(n-1)) : 1 }
  • blink(node) or Alt+B: makes a node blink for a second.
    • blink(document.links[3])
  • props(obj) or Alt+P: lists the methods and fields of an object.
    • props(document.body)
    • In Firefox, props also shows which properties belong to the object itself and which belong to objects in its prototype chain.

I’m a fan :D

The Case For JSON: What Is It and Why Use It?

[[innerindex]]

A Little Background

After my post titled Look Ma, Cross Domain Scripting! a while back, I received a comment that was seeking more information. The commenter posts:

I’m looking at your code and it doesn’t explain exactly how this works, it just provides us with code to use. I’m curious as to what makes JSON work and what differences JSON has from XML. Is there any draw-backs or negative effects of using your solution? Is it a hack that will be fixed in the future?

If you know all about JSON and are wondering why to use it…I’ll tell you right now. Speed. But…if you are curious, I’ll attempt to answer the above questions, show some examples and then I’ll re-iterate Cross-Domain Scripting.

What is JSON?

JSON (or JavaScript Object Notation) is a highly portable data interchange format. While its structure is recognized natively by Javascript (as it is Javascript), its formatting conventions are easily recognized by other C-like languages. JSON.org has an excellent description:

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.

In JSON, they take on these forms:

  • An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
  • An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
  • A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
  • A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string.

Excepting a few encoding details, that completely describes the language.

JSON Structure

Here is a graphical representation of the formatting structure (image from JSON.org):


oav

Why JSON over XML?

Alright…I can already see the hordes of people wanting to wrench my head from my neck and drive lollipop sticks up my nose. But take a step back, put down the weapons and hear me out.

XML is versatile. You can create tags to your hearts content and endlessly nest data in seemingly sensible ways. XML is well known and most savvy developers can manipulate it in all sorts of ways. So what isn’t there to like about it? It just so happens that XML is like a fat tick after a good meal…bloated. Despite its ease of creation, the amount of busy tags makes it difficult to read with the human eye. Ok…don’t get me wrong, its easier to read than a Comma Separated file, but when compared to JSON, XML makes my head hurt.

JSON is simple and can represent the exact same data with fewer characters. How? Well, there are no tags. You give a member a name and then a value. Lets compare some examples…

JSON Examples

Lets say I want to expose two quotes from my friends at Uber-Geeks in some way…lets compare them in XML and JSON.

<quotes>
  <quote>"50 degrees all week today." - Ironmule</quote>
  <quote>"He wasn't naked...he had sneakers on." -Jon Emmons</quote>
</quotes>
{quotes:[
    "\"50 degrees all week today.\" - Ironmule",
    "\"He wasn't naked...he had sneakers on.\" -Jon Emmons"
  ]
}

That doesn’t seem too different…lets try something a little more complex. How about a Konfabulator Widget?

<widget>
    <debug>on</debug>
    <window title="Sample Konfabulator Widget">
        <name>main_window</name>
        <width>500</width>
        <height>500</height>
    </window>
    <image src="Images/Sun.png" name="sun1">
        <hoffset>250</hoffset>
        <voffset>250</voffset>
        <alignment>center</alignment>
    </image>
    <text data="Click Here" size="36" style="bold">
        <name>text1</name>
        <hoffset>250</hoffset>
        <voffset>100</voffset>
        <alignment>center</alignment>
        <onmouseup>
            sun1.opacity = (sun1.opacity / 100) * 90;
        </onmouseup>
    </text>
</widget>
{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}  

The more complex the data you are trying to represent, the sexier JSON looks in comparison. Check here for some more examples…one is really long and looks quite sexy and readable in JSON and not so much in XML.

JSON and the Ajax Buzz

Ok, so if JSON and XML are pretty much peas in a pod when it comes to what they can represent, why make the switch (or at least…provide JSON). Ajax is our reason! You see, in an Ajax environment where we make calls to web services we expect to get some data back in some form. Well, if we receive XML back as a direct result of an Ajax call, we have to send that data through an XML parser before we can even begin to manipulate the data to be useful to JavaScript. If we receive the data in JSON…we don’t have to do anything but assign the results to a variable because JSON is already JavaScript. From there, we can manipulate the data as normal.

As Ajax methodologies (and even Cross Domain Scripting) become more commonplace, data format becomes vital to the efficiency of our applications. The Zimbra folks seem to have realized this and subsequently re-architected their entire application. Oh, and Script.aculo.us creator Thomas Fuchs seems to agree and states his opinion on XML in Ajax communication: Its dog slow…don’t do it.

JSON and Cross Domain Scripting

In my article Look Ma, Cross Domain Scripting, I discuss a method for doing Ajax-like calls to remote domains. As many of you may or may not know, XMLHttpRequest is restricted from making requests to remote domains.

The way it works is this: Somewhere out there exists a server side script that you wish to access in an Asynchronous fashion. Rather than attempting an XMLHttpRequest (which we know won’t work), all you do is dynamically create a <script> tag with its src set to the URL of the off-site page. When a script tag is inserted, browsers immediately execute the src! As long as the off-site page returns valid JSON, the JSON is executed locally.

For dynamically adding script tags, I use this library found over at Dan Theurer’s Blog. Its pretty simple and prevents duplicate script tags (which is a necessity).

Yahoo! sets a good example. They allow you to pass in two parameters to any of their web services (which return XML by default) and get the results in JSON.

Get JSON Output with output=json

By default the Yahoo! Web Services return output in XML format. To get output in JSON format, use the output=json parameter in the request:

http://api.search.yahoo.com/ ImageSearchService/V1/ imageSearch?appid=YahooDemo &query=Madonna&results=2 &output=json

Add a Callback with callback=function

The callback parameter (callback=function) wraps the JSON output text in parentheses and a function name of your choosing. For example:

http://api.search.yahoo.com/ ImageSearchService/V1/ imageSearch?appid=YahooDemo &query=Madonna&results=2 &output=json&callback=ws_results

This request results in this output:

ws_results( …json output… );

What is the drawback of this cross-domain solution? Well, I am relying on browsers to automatically execute the JavaScript in any dynamically created script tags. I have yet to find a mainstream browser that doesn’t…but the same goes for XMLHttpRequest. This method is used within Plymouth State University‘s live portal for Savable State Channels and we have yet to receive a support call regarding problems :)

JSON Resources

  • JSON.org: This site is the JSON site. It provides a description of what JSON is, provides some examples, and provides a list of JSON parsers for various languages.
  • Wikipedia: Enough said.
  • JSON Discussion Group
  • Yahoo’s JSON Web Services: Provides examples and suggestions on formatting your REST calls to return JSON as an option

Summary

XML works nicely. JSON works just as nicely and faster. This is why I’m a JSON fan. Speed is just as important as the data itself. Without speed…well, you’ve got crap.

Syntax Highlighting in WordPress

Some of my most recent posts involving code have displayed the wonderful blocks of login in all its syntax highlighted glory. A week ago I stumbled on the sweet syntax highlighting plugin – iG:Syntax Highligher (here’s the link to the actual plugin).

The highlighter uses GeSHi for the highlighting engine then wraps a bunch of sweet javascript functions around it to give it a bunch of features (i.e. viewing as syntax highlighted code or plain text toggle). Here’s the supported language list:

[as] & [/as]
[asp] & [/asp]
1
1
1
1
1
1
1
1
[mysql] & [/mysql]
1
1
1
1
[smarty] & [/smarty]
1
1
1
1

Installation is super easy and simply requires you to edit the quicktags.js file in wp-admin. If you’re looking for a syntax highlighter for your blog, I’d suggest you give this one a try. w00t.

Ajax; Templating; and the Separation of Layout and Logic

[[innerindex]]

The Background

I have often mentioned my process of expanding my proficiency of Ajax. Through my journey I have made a number of wrong turns and hit my share of stumbling blocks. All of that has been a learning experience and I’m learning still. I began fiddling with XMLHttpRequest as many do – blissfully ignorant of the many frameworks that exist to make Ajax super easy. My code was bloated with some neat…’features’ (pronounced: bugs).

Then I discovered the Simple Ajax Toolkit (SAJAX), which was simpler than doing raw XMLHttpRequest but really not all that simple. My latest step into the world of Ajax, and the toolkit that holds my love (currently) is Prototype…and I like my Prototype served with a side of Script.aculo.us. *drool* UPDATE: I now use jQuery for all my Ajax and DOM manipulation goodness.

While Ajax is the cause for the article, the heavy focus is on templating. For the past few years I have been using XTemplate as my templating library (I’m a PHP buff) and have been happily separating my logic from my layout…unitl I ran smack dab into the power of Javascript. My PHP still kept its separation from HTML as is the purpose of XTemplate, but it was my HTML that became littered with little nuggets of Javascript all over the place. No matter the method to my Ajax madness, this was my problem.

What Exactly Is Templating And Why Do It?

Templating is definately not new and its use has been debated back and forth for quite some time. But like I stated above, the goal of templating is to keep logic separate from layout which is a good thing for a couple of reasons:

  1. Less clutter. Face it, HTML and whatever server-side scripting language you choose to use are two different beasts. Mixing them together is visually unappealing making code hard to read…and hard to read code is hard to debug.
  2. Coders can develop code. Designers can develop layout. With templating, you are able to achieve this separation and avoid the need for a developer to butcher a designer’s layout to make it function with an application. Each can design/code on their own then combine their efforts with ease.
  3. With separation such as this, applications are more easily skinned and/or receptive to complete UI overhauls.
  4. Did I mention less clutter?

Let me give you an example of what I mean with a simple Goodbye Cruel World application:

Here’s the PHP script: goodbye.php

< ?php
include('xtemplates.php');

$tpl=new XTemplate('goodbye.tpl');
$tpl->assign('CHEEZEWHIZ','Bork, bork, bork!');

$tpl->parse('main');
$tpl->out('main');
?>

Here’s the Template: goodbye.tpl

<!-- BEGIN: main -->
  <div style="font-size:18px;font-weight:bold;">Goodbye Cruel World! {CHEEZEWHIZ}</div>
<!-- END: main -->

Here’s the output:

Goodbye Cruel World! Bork, bork, bork!

Obviously that is an extremely simplistic example. With XTemplates I can get pretty complex and include files, loop over and parse out some complex block structures, assign arrays into template variables, etc. If you want to see a more complex example of a template, check it out here.

Templating Seems Sexy, How Does It Work In An Ajax-ified Environment?

I thought you’d never ask. For this, I have created a diagram to detail how I combine Ajax, PHP, and Templating all in one.


ajax_with_templating.gif

It all works like this:

  1. A User makes a request to view a page
  2. The server-side script calls a series of application functions that generate blocks of templates
    1. Each section that can be updated/rendered by Ajax calls are separated into their own templates, which enables them to be called on initial page load and separate Ajax-triggered calls from the client.
  3. The complete template blocks are sent to the user as a rendered page.
  4. As the user interacts with the interface, two specific things can occur:
    1. An Ajax.Updater (see Script.aculo.us) is triggered, which makes an Ajax callout. The callout is sent to the Ajax Handler (which is a PHP script) which handles the call and invokes the appropriate application functions. Those functions initialize template blocks and output HTML. The HTML output by the server is received by the client and inserted into the User Interface.
    2. An Ajax.Request (see Script.aculo.us) is triggered, which makes an Ajax callout. The callout is sent to the Ajax Handler (which is a PHP script) which handles the call and invokes the appropriate application functions. No templates are initialized or output to the client…instead, the client manipulates the DOM on its own to give proper feedback to the user.
  5. Rinse and repeat as needed.

If we keep all HTML within templates and use modularized functions to initialize and render those templates, we achieve extreme layout/code reuse.

Sounds Cool…So What’s The Problem?

Well, a server-side scripting language coupled with a templating engine is all well and good. But if as we throw Ajax into the mix, suddenly we are working with a lot of Javascript in addition to the a server-side language and HTML. Through my journey in Ajax development my templates – which were havens away from code – were overrun with Javascript code! Eegad.

Now, don’t worry. I place my Javascript in separate Javascript files and include them where appropriate with ye olde <script> tag, which I have done from the beginning. No, the issue has been handling user events; onClick, onMouseOver, onMouseOut, etc. Ajax functions primarily based on user interaction, so onClicks and whatnot are core. My templates soon began to look like this:

<!-- BEGIN: stuff -->
<div>
  <div>[<a href="javascript:void(0);" onClick="Element.show('add_item');">Add</a>]</div>
  <div id="add_item" style="display:none;">
    <form id="add_item_form" onSubmit="Ajax.Request('ajax.php?'+Form.serialize('add_item_form'),{method: 'post'});return false;">
      Name: <input type="text" name="name"/> <input type="submit" value="save"/> <input type="reset" value="cancel" onClick="Element.hide('add_item');"/>
    </form>
  </div>
</div>
<!-- END: stuff -->

As you can see, the once separate layout was laden with code.

The Solution

In a fully layout separate from logic in an Ajax environment, you need to make use of Javascript event handlers. My personal choice is Behaviour which my friend, Zach, posted about yesterday.

Behaviour (coupled with Prototype) gives you easy-to-follow separation of javascript and HTML. Hugely cool. Hugely useful. Here’s an example:

The HTML:

<ul id="example">
  <li>
    <a href="/someurl">Click me to delete me</a>
  </li>
</ul>

The Javascript:

var myrules = {
  '#example li' : function(el){
    el.onclick = function(){
      Element.removeChild(this);
    }
  }
};

Behaviour.register(myrules);

That example creates a bulleted list (as is readily obvious in the HTML code). What nifty is the Behaviour Javascript logic. myrules says that any <li> tag with a parent id of #example will have an onclick that causes the li tag to be removed.

And of course, besides Behaviour there is a slew of other solutions that when combined together make for a sweet, modularized, separated solution. Here’s what I use for my PHP/Ajax applications:

Here are some standards I stick to:

  • Keep CSS (.css) styles separate from the Template files
  • Keep JavaScript (.js) files separate from Template files
  • Keep HTML in the Template, don’t spatter it around the PHP scripts
  • Modularize as much as possible
  • Heavy Code reuse

The Drawbacks

Obviously in a Templated/Event Handled environment there are some drawbacks and I’d be stupid not to mention them. Here goes:

  • There is some overhead when using a templating engine. With XTemplate, the layout engine is a PHP class that loads the template and parses through it as dictated by the application functions
  • True separation – separating out your Javascript into .js files, your CSS into .css files, your server-side scripts into various files (the initial script, a functions script, and your ajax handler(s)), and your layout into template files – generates a lot of files to deal with. The larger your application, the more you will need to micro-manage the organization of these files, which in and of itself can be a daunting task.
  • Ummm…I can’t think of any more just yet. I’m sure more will come when I’ve lived in this environment a lot longer.

Summary

Layout and Logic separation is a beautiful thing; keeping one language from another has some true value in readability. To do it half-way gains you nothing. True separation has been a blessing in my development and debugging. If you haven’t at least tried it, check it out, it may be what you were looking for (even if you didn’t know it).

Oh and a definate Kudos to Zach Tirrell for starting me down the road of templating and Gmail/Google Maps/Casey Bisson for driving me to check out Ajax.

Prototype Makes Javascript Painless

prototype.gifPrototype is an excellent tool but lacking in documentation, causing me to fumble around and *gasp* look at the source code. As any developer knows, when reviewing code there is a chance that you may miss something or ignore what doesn’t seem interesting. In doing so, you may miss some sweet features that you would otherwise use.

I did stumble upon some Prototype Cheat Sheets that have helped immensely in exposing functions that existed in Prototype that I had no clue were there. Desipte the exposure of function names, I was at a loss for what some of them did. Luckily, there is an article over at SergioPeriera.com that documents many of those functions! The documentation is fairly solid so I HIGHLY reccommend checking it out. Here’s one of the features of Prototype that I had seen the function but hadn’t a firm understanding on what it did:

Try.these()
Tries a number of functions in order. If the first fails, it attempts the second, and so on.

function getXmlNodeValue(xmlNode){
	return Try.these(
		function() {return xmlNode.text;},
		function() {return xmlNode.textContent;)
		);
}

Hugely cool. In addition, Ajaxian – which seems to be my source for many things Ajax – has pointed me towards this article over at SitePoint. I was aware of a number of the points mentioned in that SitePoint article, but a few stood out as super sexy. Here’s the juicy tidbits:

String.times([something])
Prototype adds a great method to Number, too. Say goodbye to your for loops!

// alerts "1", "2", "3" ... "50"
(50).times(function(n) { alert(n); });

Enumberable.each([something])
This does the same as a foreach in PHP. I’ve been looking for something like this!

// alerts "a is at 0" then "b is at 1" then "c is at 2"
["a", "b", "c"].each(function(item, index) {
 alert(item + " is at " + index);
});

Iterating over childNodes in the DOM
By default, even though nodes are represented in Array-like form, they do not have Enumerable available to them automatically. Here’s how to do it:

// add Enumerable to childNodes
var children = $A($("mydiv").childNodes);

// sets class="highlighted" for all child nodes of "mydiv"
children.each(function(child) {
 child.setAttribute("class", "highlighted");
});

Here’s one I found while digging around in the Prototype code that the article solidified my understanding:

Ajax.PeriodicalUpdater(id,file,options)
Periodically does an Ajax.Updater call!

new Ajax.PeriodicalUpdater("mydiv", "hello.php", {
 // initial number of seconds interval between calls
 frequency : 1,
 decay : 2
});

The decay option allows you to give your server a bit of a break if it’s returning a lot of identical responses. Essentially, every time PeriodicalUpdater makes a request, it compares the results with what the server returned last time. If the values are the same, it multiplies the interval by the decay value. So, for the above example, it would make the next request two seconds later, then four seconds later, and so on, until it received a different result from the server. At that point, the interval would be reset to one second.

Ajax.Responders.register(options)
Register global event handlers that are triggered for each and every AJAX request that happens on the page.

Ajax.Responders.register({
 onCreate : showLoader,
 onComplete : hideLoader
});

Look Ma, Cross-Domain Scripting!

Ajax, as I’ve stated time and time again, is sweet. So what is problem? XMLHTTPRequest requires that the called scripts that execute server side and return information to the client must reside on the same domain. This has irked me time and time again during my exploration and experimentation of the Web 2.0 world.

Enter JSON Web Services and dynamic script tags. This beauty allows for Ajax-like communication across domains without requiring page loads. Right right right…so how do you use it? Read on…

First, lets clarify what JSON (JavaScript Object Notation) is. Wikipedia explains that JSON is just a way to structure object data in a way that is easily interpreted…primarily with JavaScript. Here’s some examples from Wikipedia:

JSON Example:

bork({"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}});

Which is the same as this XML Example:

<menu id="file" value="File">
  <popup>
    <menuitem value="New" onclick="CreateNewDoc()" />
    <menuitem value="Open" onclick="OpenDoc()" />
    <menuitem value="Close" onclick="CloseDoc()" />
  </popup>
</menu>

So…if JSON just the data representation part of things, how does it work similarly to Ajax?

Now we’re getting into the Web Services side of things. The quick answer: When you dynamically create <script> tags on a page, the JavaScript source is executed immediately. Now, as most experimental web developers may well know, you can reference remote JavaScript source in a <script> tag. Which means….if you dynamically create a script tag that references a source on another domain, and that source outputs JSON, you are as good as gold!

Here’s the step by step: (I use a JavaScript Object I found over at Dan Theurer’s Blog for the dynamic adding of script elements…it helps avoid duplicate script tags).

First, lets make the remote file that outputs JSON. (obviously, most cases will have the data dynamically generated…but I’ll use a static example as the generation of this data is trivial)

file: remote_file.php

< ?php
echo 'bork({"Image": { "Width":500, "Height":250, "Title":"Giant Cow", "Thumbnail":{"Url":"http://someurl.com/image/1234", "Height": 75, "Width": 150}}});';
?>

Here’s the html file we want the user to see/interact with:

file: client.html

<html>
<head><title>Test</title></head>
<script src="js/jsr_class.js" type="text/javascript"></script>
<script type="text/javascript">
function addScript()
{
  var obj=new JSONscriptRequest('http://someurl.com/remote_file.php');      
  obj.buildScriptTag(); // Build the script tag      
  obj.addScriptTag(); // Execute (add) the script tag
}//end addScript

function bork(data)
{
  var text='';

  if(data==null)
    alert('error');
  else
  {
    text='Image Title: ' + data.Image.Title + '<br />';
    text+='Width: ' + data.Image.Width + '<br />';
    text+='Height: ' + data.Image.Height + '<br />';
    text+='Thumbnail Data: ' + data.Image.Thumbnail.Url;
    text+=' (' + data.Image.Thumbnail.Width + 'x' + data.Image.Thumbnail.Height + ')<br />';
  }
  document.getElementById('output').innerHTML=text;
}//end bork
</script>
<body>
<a href="#" onClick="addScript(); return false;">Click to Get Stuff</a>
<div id="output"></div>
</body>
</html>

Thats all there is to it! Simple and slick.

Deleting the Internet

I am always talking about deleting the internet. I have finally written a script that will traverse the ENTIRE internet (regardless of security) and delete everything. We’re talking images, video, text documents, pdfs, security files, EVERYTHING. It took me a while to code, but I believe it will work. I have not yet tested it as I don’t want to be the one targeted by the media. If you feel so inclined to test the script: click here.

(photo courtesy of: FreeWebs.com)