Tag Archives: Javascript

Creating a JSON API

I was assisting someone recently in building an API for their website and it occurred to me that while the current trend is generally using XML/REST/SOAP for APIs, there is quite a bit of benefit to using plain old Javascript and JSON.  Most users won’t venture into API territory, so if your goal is to make your API accessible – and this goes double if your primary purpose is embedding content in a third party site – it’s hard to argue with Javascript.

The Phish.net API, for example, is a simple HTTP request to an endpoint that returns JSON.  If you provide a callback function name as an argument, and then pre-define that function, it will return the contents wrapped in a function call.  In short, if you define a function called “example()” that accepts JSON an array/object as an argument, then by requesting the API with a callback of “example”, the response will be returned like so:

example(json response);

The benefit, of course, is that it allows a user to embed your code easily. If you host your own callback functions, you can very easily walk a user through a data embed. For example, on Phish.net, we offer the band’s latest setlist.  So we host a callback called pnet3setlist().  Then we offer the API response.  Embedding the setlist is literally as easy as this:

<script src="http://api.phish.net/callbacks/pnet3-setlist.js" type="text/javascript"></script>
<script src="https://api.phish.net/api.json?method=pnet.shows.setlist.recent&amp;amp;callback=pnet3setlist" type="text/javascript"></script>

I’m going to dig more into this later, but the gist of this is that the API can be constructed in a way that allows novice users to interact with it in their WordPress- or Blogger-blogs with little to no modification, it allows semi-skilled users to modify it slightly and tweak it for display purposes, and it allows advanced users to control virtually all aspects. Since virtually every major web language can encode and decode JSON (Javascript, PHP, Ruby, ASP, etc), it’s a near-universal way to exchange data. It doesn’t carry the overhead or complexity of XML, nor does it have the limited scope of something like serialized PHP.

Javascript-based APIs may not be the ultimate solution to a fully interconnected web, but they’re certainly going to be one of the best and simplest methods of data exchange for the foreseeable future.

Javascript Ninja!

Thank you, John Resig. Because of you, I’m learning about Javascript the way Andy Gadiel taught me HTML. In the days before server-side scripting, I learned my first bits of HTML largely by viewing the source of Andy Gadiel’s Phish page (which, for some reason, remains largely unchanged since ~1997).  By reading Gadiel’s HTML, I slowly pieced together my own understanding of HTML.  It was Joe Burns’ fantastic Javascript Goodies that first had me dipping my n00b fingers into client side active scripting.  I picked up CSS all over the web.

Resig’s jQuery is so powerful and so easy that even with basic knowledge of CSS and Javascript, anyone can be a virtual scripting master.  It’s so easy, that I’ve slacked on learning about javascript objects, inheritance, closures, anonymous functions, prototypes, and scores of  other Javascript staples that I should’ve long since mastered.   I just discovered John’s new web app, cleverly titled “Learning Advanced Javascript“, and so far, so good!

I wrote this myself and understand why it works, which is much more than I could say yesterday.

var ninja = {
	walk: function(steps,turn) {
		toDo = 'Walking '+steps+' steps forward, then turning '+turn;
		return this;
	  },
	star: function(action,distance) {
		toDo = toDo+' '+action+'ing star '+distance+' feet'; return this;
	  },
	then: function() {
		toDo = toDo+', then '; return this;
	},
	doIt: function() {
		log(toDo);
	}
}
ninja.walk('7','south').then().star('throw','50').doIt();

Output:

> Walking 7 steps forward, then turning south, then throwing star 50 feet

It’s clear to me – and has been for some time – that the future of the web, for better or for worse, rests heavily on the mighty shoulders of client side scripting.   Building on powerful, extensible frameworks like jQuery and MooTools, the next generation of web apps is sure to compete with the desktop.  The ability to understand how to utilize the frameworks when necessary and hack together powerful scriptlets for other purposes seems essential to success in the future web. I know I’ll be investing in “Secrets of a Javascript Ninja” just as a result of this tutorial.

Why Degrade Gracefully?

I got thinking today, as I near roll out of an internal helpdesk app heavily using jQuery, why we bother to degrade our scripts so they work without javascript. I get it: some people have javascript disabled in their browser… but my question is this: so what?

Javascript is a core part of web experience today.  In fact, I’d say that, on the desktop in the full browser front, if your browser doesn’t support at least HTML 4, javascript, and CSS 2, you’re not playing with the right tools.  After all, we expect that people can parse HTML, why not expect that javascript is a pre-requisite for web usage?

javascript

Some of us go to great pains to make sure our sites work should a user have javascript disabled.  But I’m actually considering the opposite: hiding certain critical elements if you don’t have javascript enabled to ensure that each visitor is on an even playing field.  Wrapping submit buttons in jQuery’s append() method, submitting data on click(), and plentifully exchanging JSON data via AJAX throughout ought to properly cripple participation of those who opt out of script execution on my site.

It all comes down to this: if you want your site to reach the widest audience possible, you need to anticipate that the client may not allow you scripting capability.  Conversely, on our intranet, and maybe one day on my websites, I’m doing the opposite: if you want to use the site, you’ve got to enable javascript: if you don’t, well… your loss.

Blinking Images With Javascript

I needed to have an image blink in one of our intranet applications today, so I wrote this quick javascript to accomodate. There aren’t many good image blinker scripts online, so I’m adding mine to the mix:

Start by adding this to your javascript file:

function blinkId(id) {
	var i = document.getElementById(id);
	if(i.style.visibility=='hidden') {
		i.style.visibility='visible';
	} else {
		i.style.visibility='hidden';
	}
    setTimeout("blinkId('"+id+"')",1000);
	return true;
}

And this right before you end your <html> tag:

<script type="text/javascript">blinkId('YOUR_ELEMENT_ID');</script>

This will work for images, divs, spans, pretty much any block level element with an id.

Updated 8/19/2008: Fixed a copy/paste bug in this post.

ACID3, Safari 3, Opera 10, Take 2

And so the real race begins. Yesterday, Opera software announced via blog post that their post Opera 9.5 builds are passing the ACID3 test. Cool!

But alas, the Webkit team – who really have a great track record of being successful with bleeding edge, one upped them by not only passing the test, but releasing the code. So behold, this is Webkit nightly for Windows, build 31368 from 2008-03-26.

ACID3 on Webkit

We know that Safari 3.1 doesn’t and Opera 9.5 won’t pass ACID3. We know IE8 is a long way off. We know Firefox 3 is still pretty far from it too. But now we have browsers that can do it. The the big question is, who will have the first stable general release that does it? Safari 3.2? Opera 10?

It’s an exciting time in web development, and I hate to admit that I think it’s largely due to IE8. If the IE team steps it up, some of themes technologies have the potential to reinvigorate the web. No serious e-commerce site would alienate all IE users – even today, they make up 80% or so of internet users. But as things progress here, we’re likely to start seeing some incredible things in the next few years.

Update: A bug in ACID3 was apparently noticed as a result of the Webkit team’s work. This awesome detailed blog post from the Webkit site chronicles the final steps of the adventure. Note that the “animation smoothness” criteria is subjectively, and that the team is apparently giving themselves a fail, but nothing that they think they are “faster than all other browsers“. Congrats again, Webkit team. Well done!

Acid 3 on Webkit Nightly

The Acid 2 test has, for a few years now, been the de facto test for your browser’s CSS capabilities. The Acid test, fewer people know, is not really about conforming to standards – passing it does not make your browser standards compliant or complete, so it’s best to understand that all it really means is that it properly handles the elements tested as well as certain errors properly. Sometime in 2005, Safari passed Acid 2, becoming the first mainline browser so earn that honor. A few years later, the current or development versions of all major browsers – including Firefox 3, IE8, Opera 9.5 – all pass the Acid 2 test.

Enter Acid 3. Acid 3 measure even more goodness, including these six “buckets”:

  • Bucket 1: DOM Traversal, DOM Range, HTTP
  • Bucket 2: DOM2 Core and DOM2 Events
  • Bucket 3: DOM2 Views, DOM2 Style, CSS 3 selectors and Media Queries
  • Bucket 4: Behavior of HTML tables and forms when manipulated by script and DOM2 HTML
  • Bucket 5: Tests from the Acid3 Competition (SVG,[5] HTML, SMIL, Unicode…)
  • Bucket 6: ECMAScript

Using recent browsers, everything fails pretty spectacularly. My Opera 9.26 install gets a 42/100. Safari (including iPhone) does 39/100. IE7 does 12/100, Firefox 2 does the most respectable with 52/100. Even IE8 only does 17/100 while Firefox 3 tops out at 59/100 and Opera 9.5 at 60/100. The current generation, even the next generation of major browsers are still far from coming close to rendering Acid 3 with any accuracy.

I have been playing, now and again, with Webkit nightlies, since Webkit is actually a really neat engine, and guess what it kicks out? This:


Webkit nightly on Windows Vista

Pretty impressive. Safari is pretty limited when it comes to extending its function – it doesn’t even support a “new tab” button. But the webkit and javascript core engines are respectable both in rendering skill and speed.