CouchDB with YUI Datatable

I am not kidding, this must be the easiest way to get a ajaxy table of results from a database. For those who haven't heard the buzz, CouchDB is a document-based database. I am not an expert in databases so I won't really comment about CouchDB itself. One incredible feature is that the database server is queryable over HTTP (with REST) and responds with JSON, which seems perfect for writing pure Javascript applications.

YUI probably needs no introduction. I think its the best JavaScript library for maintainability, and documentation. It sometimes seems a bit verbose, but I like verbose.

Note: You will have to get around the fact that you cannot make XHR requests to a server other than the server that the page lives on, either with a reverse proxy setup, or by hosting the files themselves in CouchDB. (I won't explain that here).

So, a basic request to a database to return all the documents goes something like this:

a GET to:

http://myserver/dbname/_all_docs

And that will return a JSON data structure. In our case, each document has a "title" attribute and a "description" attribute, and the "rows" member of the return JSON contains a list of these.

Our database is called "tickets" and you could imagine it is a ticket tracking application.


function list_tickets() {
var myDataSource = new YAHOO.util.DataSource("/tickets/_all_docs");
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;

// Define the data schema
myDataSource.responseSchema = {
resultsList: "rows", // Dot notation to results array
fields: ["id", "title","description"] // Field names
};

// Define how it will appear in the table
var myColumnDefs = [
{key:"id", label:"Ticket ID"},
{key:"title", label:"Ticket Title"},
{key:"description", label:"Ticket Description"}
];

var myDataTable = new YAHOO.widget.DataTable("table_holder", myColumnDefs, myDataSource);
}


Just make sure you have a <div id="table_holder"> somewhere in your document, because this is what will be replaced by the data table.

That's really it. No web server application, no PHP (or Python or Ruby or Perl). Just javascript talking to your database. Incredible.

Popular posts from this blog

PyGTK, Py2exe, and Inno setup for single-file Windows installers

ESP-IDF for Arduino Users, Tutorials Part 2: Delay

How to install IronPython2 with Mono on Ubuntu