Archive: Ajax

May 12, 2008

Cross browser session data with Javascript

By storing data in the window.name property, you can store data between page loads and across domains without ever sending a cookie to a server. Thomas Frank created the sessvars.js library which makes use of this browser quirk, allowing you to store up to 2 MB of client-side session data.

This is really powerful for a few reasons:

  • client-side, you can store way more data than allowed by traditional cookies
  • none of the data is transferred explicitly to the server, minimizing bandwidth used for each page request
  • allows you to talk between pages in different domains

Keep in mind that anything you store via this mechanism will be visible to any other site that a person visits, so this is best for storing non-sensitive data that you want to retain between page loads. This would be great for caching returned AJAX data that you would otherwise have to refetch and reprocess.

Session variables without cookies

Posted by Jason Striegel | May 12, 2008 07:26 PM
Ajax, Web | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

May 10, 2008

Reading EXIF data from images in Javascript

javascriptexif_20080510.jpg

Jacob Seidelin figured out a way to obtain EXIF data from images in Javascript, allowing AJAX applications to pull information about the make and model of camera used, as well as any aperture, focal length, or description information that may have been tagged to an image by the camera or a photo editor.

The exif.js javascript library scans through all IMG tags in your HTML document, looking for the custom exif="true" parameter to be set. The DOM image object doesn't contain the necessary raw image data, so XMLHttpRequest is used to fetch the image data. In Safari and Firefox, the responseText property contains the binary image data. This isn't available in IE, however, but Jacob was able to put together a VBScript alternative that is still able to pull the data from the response.

From your code, pulling the EXIF data for an image becomes as simple as this:

var theimg = document.getElementById("imageid");

alert("Image Make: " + EXIF.getTag(theimg, "Make") + "\nImage Model: " + EXIF.getTag(theimg, "Model"));

How cool is that? I expect we'll see this in every ajax photo gallery soon.

Reading EXIF data with Javascript

Posted by Jason Striegel | May 10, 2008 08:52 PM
Ajax, Photography | Permalink | Comments (1) | TrackBack | Digg It | Tag w/del.icio.us

May 9, 2008

Processing.js - visualization library for Javascript

jsprocessing_20080509.jpg

John Resig, of jQuery fame, released a port of the Processing visualization language for Javascript. Seriously, John is on fire:

The first portion of the project was writing a parser to dynamically convert code written in the Processing language, to JavaScript. This involves a lot of gnarly regular expressions chewing up the code, spitting it out in a format that the browser understands.

It works "fairly well" (in that it's able to handle anything that the processing.org web site throws at it) but I'm sure its total scope is limited (until a proper parser is involved). I felt bad about tackling this using regular expressions until I found out that the original Processing code base did it in the same manner (they now use a real parser, naturally).

The full 2D API is implemented, with the exclusion of some features here and there between browsers (Firefox 3 is pretty full featured). You can interact with the Processing API directly from standard Javascript. This lets you make use of these drawing features by simply instantiating a Processing object, and then calling its various drawing methods.

Another capability is to write code natively in the Processing language. This allows you to make use of extended language features such as method overloading and classic inheritance, though it looks like type information is pretty much ignored.

John has many of the demos from processing.org working. Most of them are going to peg your CPU, but this is some seriously cool stuff to see working in a first release.

Javascript just got a lot more interesting.

Processing.js
Processing: open source data visualization language

Posted by Jason Striegel | May 9, 2008 09:36 PM
Ajax, Data, Firefox, Software Engineering, Web | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

April 13, 2008

Nice overview of the YouTube API

I caught this self-referential tutorial on YouTube today which walks you through the basics of the YouTube API. It appears to be quite simple to develop Javascript or Flash applications that can control or interact with the YouTube player, or even completely reskin the interface.

What I didn't know until recently was that the API has provisions for allowing your application to upload videos and post comments. You can even authenticate users and allow them to interact with the YouTube backend through your private application. It looks like you can do just about everything programatically except remove the YouTube watermark on the video.

YouTube Developer's Guide
Developer API Blog

Posted by Jason Striegel | Apr 13, 2008 11:12 PM
Ajax, Flash, Web, YouTube | Permalink | Comments (1) | TrackBack | Digg It | Tag w/del.icio.us

April 11, 2008

Automatic outbound link analytics with jQuery

I had the challenge of adding Google Analytics tracking code to all the outbound links on a site I've been working on. There are hundreds of these links scattered around the site, so rather than try and edit a bunch of links, manually adding onclick handlers in an error-prone fashion, I decided to get lazy and write some code to handle it for me.

First I was thinking about doing some sort of regular expression search and replace throughout the site and database, but that reminded me of CSS3 selectors and their ability to do simple pattern matching. I've seen people apply a special style to outbound links this way, so after a few minutes of monkeying around with things, I now have a chunk of jQuery that will automatically track clicks on all outbound links.

Here it is, in a nutshell:

jQuery(function($){

   // Match all anchor tags in the "maincontent" div with
   // urls that begin with "http" but don't contain the
   // string "yourwebsite.com"
   $('#maincontent a[href^="http"]').not('a[href*="yourwebsite.com"]').click(function(){

     try {

     // Get the href url and toss out the "http://"
     var href = $(this).attr('href');
     if ( href.indexOf("://") > 0 ) {

       // Track the page in Google Analytics as
       // "/tracking/outbound/www.somesite.com/foo"
       var outbound = '/tracking/outbound/' + href.split("://",2)[1];
       pageTracker._trackPageview(outbound);

       }
     } catch( e ) {}
   }
}

With this running, all of my internal pages get tracked as usual, and any external links will appear as pageviews that look like "/tracking/outbound/www.somesite.com/foo".

If you link out to many different pages on several sites, keeping the full site url in the tracking code and building these deep paths is particularly useful. Google Analytics will allow you to drill down into the tree like it was normal content and quickly pull numbers on how many total outbound clicks you received (/tracking/outbound), how many went to www.somesite.com (/tracking/outbound/www.somesite.com), and how many people clicked out to a particular page on the site.

This saved me quite a bit of time and is immensely more flexible than any other outbound tracking method I've used. I hope this helps someone else. Drop me a line in the comments if this works out for you.

Update: it looks like I wasn't the first to do this. An article by Rebecca Murphey shows how to do something similar, while also adding the referring post title to the tracking code. Pretty cool stuff, I must say.

Posted by Jason Striegel | Apr 11, 2008 10:57 PM
Ajax, Google, Statistics, Web, Web Site Measurement | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

April 8, 2008

Relational database using jQuery and HTML tables

Here's a novel use for the HTML <TABLE> tag: storing client side database tables. Nick Kallen came up with a slick hack that uses the jQuery syntax to perform simple selects and joins on HTML tables. By using CSS3 selectors, you can easily target fields which match or contain your search terms, and Nick's jQuery-based API provides a simple query language, similar to a rudimentary SQL:

Today I was thinking aloud about Tree Regular Expressions and how they might make a nice query language for document databases like CouchDB. Someone pointed out that CSS3 selectors might make a great concrete syntax for this. One thing lead to another and I thought, why not build a relational database in HTML? So I did. I even got inner joins working.

Let's start with a few tables:

<table class="users">
  <tr>
    <td class="id">1</td>
    <td class="first_name">amy</td>
    <td class="last_name">bobamy</td>
  </tr> 
  ...
</table>
<table class="photos">
  <tr>
    <td class="id">1</td>
    <td class="user_id">1</td>
    <td class="url">http://www.example.com/foo.png</td>
  </tr> 
</table>

Now we can express some queries:

$('.users')
  .where('.id:eq(1)')
  .select('*')

This is equivalent to SELECT * FROM users WHERE id = 1

$('.users')
  .where('.id:eq(1)')
  .select('.id, .name')

This is equivalent to SELECT id, name FROM users WHERE id = 1

How cool is that? Check out Nick's blog post for an example of text search and an inner join. The API in his jquery.db.js is quite straightforward and only about 50 lines of code. Adding a sort function shouldn't be too difficult.

I'm pretty much convinced now that jQuery is black magic.


Building a relational database using jQuery and <TABLE> tags
Download the jquery.db.js library

Posted by Jason Striegel | Apr 8, 2008 10:02 PM
Ajax, SQL, Software Engineering, Web | Permalink | Comments (1) | TrackBack | Digg It | Tag w/del.icio.us

January 18, 2008

Homebrew Google Analytics API

analyticsapi_20080118.jpg

It's too bad that Google Analytics doesn't have an official API, but Chris Riley came up with a fun solution for pushing analytics content into a format that is easily accessible from your web applications.

Using Google Analytics' scheduled reporting feature, you can have an analytics report automatically sent to a public, read-only Google Group in XML format. From there, the group's latest post can be pulled in through Yahoo pipes where it is filtered and exposed as a JSON service, ready for you to pull into a web application via Javascript. Yoikes!

Chris' example shows you how to do this to add a popular posts feature to your blog. You should be able to tweak the code to export other information from Analytics as well, including geographic distribution, popular search terms, or even visitor and pageview data.

No Google Analytics API? No Problem! - Link

Posted by Jason Striegel | Jan 18, 2008 09:04 PM
Ajax, Google, Web, Yahoo! | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

July 10, 2007

Server-side Javascript/DOM - search friendly AJAX?

John Resig posted yesterday about his experiments with creating a full Javascript/DOM pseudo-browser environment that runs from the command line:

This weekend I took a big step in upping the ante for JavaScript as a Language. At some point last Friday evening I started coding and didn't stop until sometime mid-Monday. The result is a good-enough browser/DOM environment, written in JavaScript, that runs on top of Rhino; capable of running jQuery, Prototype, and MochiKit (at the very least).

The really nice touch is that you can issue PUT and DELETE requests on the XMLHttpRequest object to manipulate files on the local file system! Here's an example script that scrapes post titles from alistapart.com and stores them in a file (remember, this runs on the server like a shell script):

load("env.js");
window.location = "http://alistapart.com/";
window.onload = function(){
  load("dist/jquery.js");
  var str = "Newest A List Apart Posts:\n";
  $("h4.title").each(function(){
    str += " - " + this.textContent + "\n";
  });
  var out = new XMLHttpRequest();
  out.open("PUT", "file:/tmp/alist.txt");
  out.send( str );
};
Read full story

Posted by Jason Striegel | Jul 10, 2007 10:23 PM
Ajax, Java, Web | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

July 2, 2007

Client-side SQL database in Javascript

trimquery_20070702.jpg

I was thinking today about how a person might go about creating a rich offline web application for devices like the iPhone, where your application may need to run entirely from cache from time to time.

In the extreme example, you could imagine an application that stored its data entirely on the client side, and used cached html and javascript files to manipulate that data. Assuming you could get around the storage issue -- either via cookies, a Flash shared object (not available for the iPhone), Firefox or IEs storage objects, or some trickery with browser form autocompletion -- you'd still run into the task of manipulating that data.

Web developers are used to using an SQL database for the retrieval, joining and sorting of data, so it's convenient that similar functionality exists within Javascript, thanks to a small Javascript library called TrimQuery. After defining a simple table schema, you can use TrimQuery to issue a subset of the standard SELECT syntax. This will let you do something like the following, all within Javascript:

selectStatement = queryLang.parseSQL( "SELECT table1.columna, table2.columnb 
  FROM table1, table2 
  WHERE table1.id = table2.fkid 
  ORDER BY table1.columna" );
var results = selectStatement.filter( tabledata );
for (var i = 0; i < results.length; i++) {
  var record = results[i];
  // ...
}

TrimQuery Demo - Link
TrimQuery: Javascript SQL Library - Link

Posted by Jason Striegel | Jul 2, 2007 07:45 PM
Ajax, Web | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

June 20, 2007

HOWTO use the Wiimote buttons in Flash

wiimote_20070620-1.jpg
A while back, WiiNintendo posted the keycodes that are detectable by Javascript when the Wii's buttons are pressed. With this ability, you can create Javascript games that will play on your Wii. Unfortunately, even though the Wii browser ships with the Flash plugin, those keycodes cannot be detected natively in the Flash environment.

Quasimondo came up with a really clever hack that solves the problem. You can create a second flash movie and use Javascript to resize it to specific widths for particular keycodes. Even though Flash cannot detect the keycodes, it does receive an onResize event. When it receives this event, it then retrieves its current width, which was set to the value of the keycode. This second swf file can then use Flash's LocalConnection to communicate that value to the primary swf.

How to Make the Wiimote Work in Flash - Link
Aral Balkan's discussion on using the Wiimote in Flash - Link
Wiimote Key Codes @ WiiNintendo - Link

Posted by Jason Striegel | Jun 20, 2007 08:24 PM
Ajax, Flash, Gaming, Web | Permalink | Comments (2) | TrackBack | Digg It | Tag w/del.icio.us

May 30, 2007

Gears API: create web apps that work offline

gears_20070530.jpg
Google released a new Javascript API today called Gears that makes it possible to write modeless web applications that will function offline. A browser plugin is available for IE and Firefox (OS X, Linux, and Windows), with Safari support planned for the near future. The plugin will need to be installed by users of Gears-enabled applications.

From what I can see--and keep in mind that I haven't used the API yet--there are 3 basic services that the API provides:

  • local file resource storage and caching so that you can view files after disconnecting
  • a client-side SQL database that can be used by Javascript to store and fetch data
  • a worker pool module for running asynchronous background processes

The obvious use for this is to make stateful applications that continue to operate when you're offline, but maybe there are some privacy opportunities here too. Today, applications come in primarily two varieties: apps with user data and software stored locally, and web-based applications that execute and store data on the server. What I'm curious to see is if developers will begin making a third, hybrid category of application, where software release and maintenance is web-based and global data is available for local consumption, but the storage and processing of user-specific data takes place on the client side, safe from unwanted profiling.

Google Gears API Developer's Guide - Link

Posted by Jason Striegel | May 30, 2007 07:36 PM
Ajax, Data, Google, Web | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

April 25, 2007

Unofficial Google Translate API

gtranslate_20070425.jpg
The Unofficial Google Translate API is a combination javascript library and php service that allows you to do AJAX-style language translation. The PHP script serves as proxy to Google's Translate utility, passing data to and from Google on behalf of the javascript code.

Unofficial Google Translate API -Link.
Inspired by Philipp Lenssen's Google Translate API "Announcement From 2009" -Link.

Posted by Jason Striegel | Apr 25, 2007 09:10 PM
Ajax, Google, Language | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

April 18, 2007

Dynamic Javascript Chart Plotting With PlotKit

plotkit_20070418.jpg
PlotKit is a slick javascript library that allows you to easily generate line, bar, and pie charts with a few lines of javascript code. It supports rendering to both Canvas and SVG, so you can use it to add charting to your application and still be able to support a fair amount of browsers.

I'm glossing over some of the more advanced features, but check out how easy it is to generate a simple graph:


var data = [[0,0], [1,2], [2,3], [3, 7], [4, 8], [5, 6]];
var plotter = EasyPlot("line", {}, $("example"), [data]);

That will plot the values from the "data" array and display it in a div with the ID "example". Cool, no?

Charting from javascript is interesting, because it allows you to link in to data APIs that are provided by other services. There's a link below to a tool that will pull in data from a published Google Spreadsheet and generate the necessary javascript to display widget graphs on another site. It reminds me of how you can pull Excel graphs into a Word document, except javascript is the new, better OLE. With output tools like PlotKit, online services like Google Spreadsheets, and open data APIs in between, there are just so many possibilities now for creating information that can be shared in a variety of formats.

Posted by Jason Striegel | Apr 18, 2007 08:18 PM
Ajax | Permalink | Comments (2) | TrackBack | Digg It | Tag w/del.icio.us

March 26, 2007

Picasa Data API

Take a peek at Google's new GData API for Picasa. In addition to providing RSS feeds for albums, tagged photos and user comments, you can use the API to add and remove photos, albums, comments and tags from your own applications. This might be a nice way to manage image data (and offload image storage) within a web app.

Resources:

Posted by Jason Striegel | Mar 26, 2007 08:06 PM
Ajax, Google, Photography | Permalink | Comments (0) | TrackBack | Digg It | Tag w/del.icio.us

February 3, 2007

Simple Zip Code Geocoding

mpls_20070203.jpg

The ability to geocode, or translate into latitude and longitude, postal codes is a fairly useful hack to have in your programming toolbox. Quick and dirty zip geocoding allows you to do some neat things fairly efficiently and with a minimal amount of code. Though it's U.S. centric, it allows you to add location-based functionality to your apps without requiring any real personal information to be transfered or stored.

If your application only needs to convert a zip code (or any address) into a lat/lon coordinate, say for simple mapping purposes, the easiest solution is to use the Google Maps Geocoding API. In addition to the client-side javascript functionality, you can directly query the geocoding system from php using an http request like this:

http://maps.google.com/maps/geo?q=12345&output=xml&key=yourkeyhere

Just change 12345 to the zip (or any address) that you are looking up, and "yourkeyhere" should be your Google Map API key, which you can obtain here. Developer.com has a good PHP example for making use of the returned XML in your server-side code.

Often times, it's useful to be able to do zip lookups based on a geographic region. Maybe you want a list of all zip codes within a certain radius or bounding box. Applications for this could include clustering map items that are near eachother, or searching a database for items that are nearest to a given location. For this, it's really nice to have a MySQL table that contains zip codes along with their lat/lon coordinates. Fortunately, several people have compiled this sort of information from public domain data, and you can even download a full MySQL table dump here, for free.

At this point, it's a pretty simple matter to query the database for location-based information. For instance, let's say you have a web site with a guestbook that allows guests to leave their name and zip. You could easily whip up an application that tells your guests how many other guests are in their area by using a basic bounding box with a query like this:

SELECT guest.name from guest, zipcode
WHERE guest.zip = zipcode.zip
AND zipcode.lat < [maxlat] AND zipcode.lat > [minlat]
AND zipcode.lng < [maxlng] AND zipcode.lng > [minlng]

These are just a few ideas, but hopefully this should be enough to get you started. If you have some good ideas for other geocoding applications (or any mapping/gis hacks in general), please give us a shout in the comments.

Posted by Jason Striegel | Feb 3, 2007 09:42 PM
Ajax, Google Maps, Mapping, MySQL | Permalink | Comments (3) | TrackBack | Digg It | Tag w/del.icio.us

Bloggers

Welcome to the Hacks Blog!

Brian Jepson.Brian Jepson


Jason Striegel.Jason Striegel


Philip Torrone.Phillip Torrone



See all of the books in the Hacks Series!
Advertise here.

Recent Posts

www.flickr.com
photos in Hacks More photos in Hacks