Friday 23 March 2012

Listing files without server side code

Last day I had a request from a client to make a webpage for his company. No big deal, 5 or 6 static pages with a little css would do the deal. Then he asked me if it would be possible to create a side menu which contained links to files in pdf format. He also wanted to be able to manage those pdf's independently.

A whole other story for me at that point. I needed server side code to create the links to the pdf's and also a private "members" area with authentication for managing the files. Still no problem but I was wondering if I realy needed server side code.

Applying the most valuable progamming skill (KISS) I came up with a solution where I
  • enabled folder browsing on a folder that contained the pdf's
  • fetched the page that my webserver (IIS in my case) created when browsing to the folder with a jquery ajax call
  • distilled the links to <a> tags with a href ending in ".pdf"
  • parsed this into some format I liked and added them to an existing div
  • created a ftp user for the client so he could manage the pdf's

Here's the javascript code

$(function(){
   $.ajax({
      url: "./newsletters/", 
      success: function(data, textStatus, jqXHR){   
         $('a[href$=".pdf"]',data).each(function(){
            $("#latestpdf").append(this);
         });        
      } 
   });
});

Anything that solves my problem in about 2 lines of code deserves a post.