6 entries in JavaScript

I love CodeIgniter!

A brief introduction to the wonderful PHP CodeIgniter framework

Monday, June 30th, 2008

I don't normally write a post unless I'm specifically publishing code, but I wanted to write a brief post about Code Igniter as it's the best damn thing I've discovered since jQuery!

Overview

If you haven't heard of it already, CodeIgniter is a rapid application-development framework for PHP that uses the Model-View-Controller pattern to separate the presentation, logic and data from each other whilst building your web application.

What this means in practice is that instead of building one large linear PHP file that...

  1. Contains swathes of PHP in the head to filter user input (logic), then
  2. Gets results from a database (data) and does something meaningful with them, then finally
  3. Outputs the HTML (presentation) and continues to escape in and out of PHP during the process

...you end up working on many different smaller files that do one task only, with which the framework pieces together for you to deliver finished web pages.

However, before I delve into MVC, I want to touch upon CodeIgniters excellent class library.

A excellent and fully-integrated set of Library classes

The primary reason I started using CodeIgniter in the first place, is that it provides an incredibly robust and integrated set of classes to handle everything web-app related, from database classes, to session classes, to file uploading and email.

Had it not been for the fact that you have to use them within the overall CodeIgniter structure, I may well have gone off and carried on the way I was going, with logic at the top of my pages, and presentation at the bottom.

However, in order to actually use them, you have to accept you'll start coding within the CodeIgniter framework, and things will never be the same again...

An intelligent and modular approach to building web applications

The vast majority of what you do within CodeIgniter will be written within class files, that will fall under one of the three MVC areas:

  1. Controllers - classes responsible for making overall decisions, such as deciding what task is being undertaken in response to user-input, as well as loading supporting classes and logic to get the job done. Controllers are the first step in processing a task, and outputting a web page.

    It helps to think of controllers and their methods as the "folder" and "page" structure of a site. For example a "Home Controller" might have an "index" function would handle loading the home page, whilst a "Messaging Controller" and might have a "List" and "Compose" methods would handle listing messages, composing new messages, etc.

    Both these methods would take high-level decisions about the task in hand, offloading the drudgery of the tasks to other elements, such as...

  2. Models - classes responsible for everything "data" related, such as read and writing from databases, storing representations of said data, configuration, etc.

    In practice, what this means is that a Controller would never read or write data directly, it would hand all responsibility for that to a Model, and would just make calls such as "get the last 10 unread messages". The model would do the grunt-work, leaving the Controller to get on with more important things.

  3. Views - static or dynamic files that are read by CodeIgniter, populated with data, and are output to the user. Views are analogous with the final page output you'd see in procedural PHP programming.

    A view file need not be an entire web page, it could just be a segment, such as a sidebar, a form, a graph, a header, or a footer. By combining views, you have a lot of power with regards to the output of the final page, as well as a really flexible way to store individual representations of data.

    For example, depending on user input, you could load either a Table View or a Graph View that would be populated by the Model data. Inside the view you'd have written code that would receive Model data and would know what to do with it.

The benefit of this approach is that it's much easier and quicker to build and maintain your site, as everything's modular, and can be loaded and swapped out according to the task at hand (and no more huge sprawling pages).

There aren't really that many downsides to this approach, but it can be a little tricky sometimes, as due to the way CodeIgniter works behind teh scenes, you don't work with a traditional one-to-one file / page structure, but once you're used to it, you'll never want to go back.

jQuery Favelet

Add jQuery functionality to any browsable web page

Saturday, February 23rd, 2008

Any developer worth his salt knows about Firebug and its JavaScript console. I use it all the time to tinker with web pages, test stuff out and debug my own pages.

But sometimes, if I'm *cough* hacking *cough cough* someone else's page, I need the added power of jQuery! But what if the page doesn't have it?

Simple - load jQuery from a remote source manually through a javascript: call.

Save Favelet

Just drag the link below to your Links toolbar, then click it on any page to jQuery-enable it.

Add jQuery to page

Test it out!

Save the Favelet and click on it (or just click the link above), then: animate page.

Simple!

jQuery “Highlight” plugin

Highlight a form field’s parent tag (or any other selector) as you tab into it.

Tuesday, February 12th, 2008

Highlight increases usability by highlighting elements as you interact with the page.

Its primary use is for forms, but it can also be used for tables, lists, or any element you specify. It can also be used to toggle elements on and off, for example, table rows.

Examples uses:

  • Form-filling can be made clearer by highlighting the element around a control as you tab into it
  • Table rows can be made more visible as you pass the mouse over them, or click them
  • Elements can be toggled as you click them

Code example

Because of the defaults, basic usage can be as simple as:

$('form').highlight()

The method signature for Highlight is:

$(selector).highlight(parentSelector, highlightClass, startEvent, endEvent)

Demo

View the Highlight demo which has examples for forms, tables, and lists.

Download

jQuery “Populate” plugin

Populate a form or an element's child elements using a JSON object.

Tuesday, February 12th, 2008

I don't like mixing HTML and PHP when I build my forms. Instead I like to keep my HTML completely clean, then if a form needs to be pre-filled (for example retrieving a bunch of database results), get JavaScript to fill it in for me after the page has loaded.

This plugin supports full PHP naming and deep data structures, as well as checkbox arrays and other non-standard UI controls. The plugin can be used as part of your AJAX toolkit, or for separating server-side code from HTML by populating a form after the page has loaded eg:

$('form').populate({text:'text', radio:1})

and not inline as the page is processed, such as:

<input type="text" name="text" id="text" value="<?php echo $text; ?>" />
<input type="radio" name="radio" id="radio-1" checked="<?php echo $val == 1; ?>" />
<input type="radio" name="radio" id="radio-2" checked="<?php echo $val == 2; ?>" />

You can also populate non-form controls such as <div>s, by specifiying the id and an identifying attribute (defaults to id):

$('div').populate({'text-1':'text', 'text-2':'More text'})

This can be useful when you want to show the results of a database call, but don't want the text to be editable.

Instructions and demos

I've now FINALLY put up a full set of instructions and a working demo, with examples of:

  • Populating a simple form, using string variable types for textfields, radiobuttons, dropdowns and checkboxes
  • Populating a complex form, using array variable types for checkbox arrays and multi-list boxes
  • Populating a hierarchical form, using hierarchical JSON data

View the jQuery Populate Demo here.

Download

JavaScript

PHP

Form builder

Convert a list of text into fully validated, accessible HTML form controls

Monday, February 11th, 2008

I've got really, really tired of re-inventing the wheel (alright, HTML, CSS, JavaScript) every time when it comes to site forms.

I do so much database stuff these days that seems to be virtually every site I'm starting from scratch, or hacking an old site's template to work on a new site. Then once the CSS has been hammered out, comes the laborious task of form validation - tidying up all the names and ids, dusting off my RegExp-foo to validate emails, usernames, etc, etc.

It's very time-consuming and just feels like I'm missing a trick!

Wouldn't it be great if there was a magic bullet to convert a list of text into fully validated, accessible HTML form controls!?

Form Builder

Enter "Form Builder" - an online JavaScript application that will build accessible, cross-platform and validated form HTML in literally 10 seconds flat. Just type or paste in your form labels, edit some options (if you want to) and view the Live Preview and HTML.

Form builder does pretty much everything you might want...

So I've done some hard research and have employed best-practices for:

  • HTML Code
  • Styling
  • Accessibility
  • Validation

For example, what about:

  • Ease of use: copy all your labels to one text field and a whole set of controls built on linebreaks, tabs, commas
  • Live preview: not happy with the code? Edit the HTML and watch the Live Preview update
  • Intelligent attribute naming: for example, a form label is "Blood pressure (mmHg)", your names and ids are truncated at the first illegal character and re-named "blood_pressure" / "blood-pressure"
  • Automatic values: values are automatically built from the label names, or you can just paste in another list of values
  • PHP (or other) naming styles: specify a data sub-group, or use your own square bracket naming [] to group data into discrete chunks
  • Accessible HTML: all controls are married with labels, and where appropriate wrapped within <fieldset> tags
  • Validation: Optionally include basic validation attributes on elements using jQuery's Validation plugin.

Jump in and play here, then go do something more useful with all that spare time!

Adding Google Analytics to your web pages dynamically

Single-script Google Analytics inclusion

Friday, December 7th, 2007

I've just started using Google Analytics and it f*cking rocks. It's simply amazing the amount of information it provides, but more amazing still is the way it shows you how people are using your site.

Installation is as easy as copy and pasting two scripts into each web page you want tracked. What could be easier than that!? Well, how about one script?

Here's the code needed to run the tracking functions automatically:

<script type="text/javascript" src="js/google-analytics.js"></script>

Here's the code to load the tracking functions without running them (works in ALL browsers, not just IE!) so you can call the code yourself later (for example, tracking an AJAX call):

<script type="text/javascript" src="js/google-analytics.js" defer="defer"></script>

Of course, there's a few of these out there already, but here's the specifics on my take:

  • easy: a single external script that loads the Google code dynamically
  • intelligent: calls tracking function only when remote script has fully downloaded
  • versatile: use of defer attribute to run automatically (or not)
  • customizable: provides a wrapper function to execute your own custom code
  • tidy: intermediate setup variables are created privately via a function closure

Just be sure to add your tracking id to the initialization function!

Download google-analytics.js