Coding with Jesse

Ajax Security

Now and then, I hear concerns about Ajax security holes. Everytime this happens, I have to stop and think for a second. What security holes? Have I missed something? Can my visitors drag-and-drop their way into my database, or use Yellow Fade Techniques to gain root on my web server?

Here's what XMLHTTPRequest does: it's a JavaScript command to load a URL from a server and do something with the response. As long as you have security on all the URLs on your web system, you have a secure web system. Ajax isn't going to find a back door that wasn't already available to anyone with a web browser.

There is no security threat to your web server from people using Ajax. In fact, the only new security threat comes from the other direction: web sites using Ajax to spy on people.

First, let's be clear about one thing: XMLHTTPRequest isn't allowed to load code from a different server. In Firefox, this is called the same-origin policy. Other browsers have similar policies. This means that the only web page that can be spying on you is the only you're looking at and using. And the only thing that can be spyed is the way you use that web page.

So how can Ajax be used against you? Well, every time you move your mouse, a message can be sent to the web server to record your X and Y position! Or the text you're typing into a text box can be sent before you're finished spell checking! Or maybe, if the web site is evil enough, the server will record every time you click on a link! Of course, these are hardly security holes. A mild invasion of privacy perhaps, but how many web sites already have outgoing links forward through a URL-tracking service? And this is even already implemented in Firefox 2.0 as a ping attribute to the a tag!

Web sites still have no way to look at your hard drive, upload files without your knowledge, or do anything else outside of the actual web page. Ajax won't be able to spy on your after you've left the evil web site. And actually, all of this evil behaviour was possible before XMLHTTPRequest came along, using hidden iframes or document.write('<script>') or many other techniques.

So yes, with any client-server interaction there is a potential for security problems. This is nothing new to Ajax or even JavaScript. If you are especially paranoid and want to keep your mouse position secret, you can still disable JavaScript. Otherwise, the web is still a safe place to be.

Published on May 30th, 2006. © Jesse Skinner

Firebug 0.4

If you haven't yet, go get the Firebug 0.4 extension for Firefox from Joe Hewitt. Roger Johansson mentioned it, and Justin Palmer posted an in-depth walk through of the many really great features in Firebug.

The days of using alert() for debugging are over (except, perhaps, in other browsers. You can log messages and objects to the console (at info, warn, debug and error levels), trace execution, and even fire up a breakpoint with the keyword 'debugger'! Not to mention all the typical error reporting stuff and DOM walkthrough features you'd expect. Go check it out!

Published on May 30th, 2006. © Jesse Skinner

JavaScript 2 and The Future Of The Web

I just tripped across a slideshow from a talk by Mozilla's Brendan Eich at XTech 2006 titled JavaScript 2 and the Future Of The Web. Yes, I found it when I was ego searching. Regardless, it's a great talk outlining the future of JavaScript and all the new, great changes we can expect to see come out over the next two years.

I'm curious to see how quickly JavaScript 2 will be adopted by the other browsers, and how quickly web developers will start using it. I'm a bit worried that the web will be 'broken' while we wait for people to upgrade their browsers. Apparently there will be offline tools to convert JavaScript 2 code to work in older browsers. Still, I'm not looking forward to an era of having to test things across an even wider range of browsers.

The new syntax will allow for Object-Oriented coding, closures, iterators and generators to be a lot cleaner and easier, but there's nothing that isn't possible in the current JavaScript using different syntax. Even though I'm looking forward to using this new syntax, I think I'll stick with using the current state of JavaScript for the next few years even if it makes my code a bit longer and messier.

Published on May 27th, 2006. © Jesse Skinner

Using Ajax Without Server-Side Scripting

Ajax, by which I mean XMLHTTPRequest, is almost always used with some sort of server platform, such as PHP or Java, usually to retrieve data from a database. This might scare off some people from using XMLHTTPRequest, especially those who don't have the ability or knowledge to do server-side scripting. This is fine. You can actually do some things without it. I'll do a simple example with populating select boxes.

HTML

First off, we need some HTML to work with. For this example, we'll have two select boxes. When the first one changes, we want the second one to fill up with data from the server.

<form>
    <select id="one">
        <option value="">Please choose one...</option>
        <option value="colours">Colours</option>
        <option value="numbers">Numbers</option>
        <option value="letters">Letters</option>
    </select>

    <select id="two">
    </select>
</form>

Data

Now we need some data files. Before I begin, I'll just mention that there are several ways to get back data from the server. Some people use XML, others use something called JSON which stands for JavaScript Object Notation, you can also get back raw HTML or JavaScript, and then there are other ways as well. For this example, I'm going to use JSON because it's pretty simple. You can do really advanced stuff with JSON, but I'm just going to use a JavaScript array. I'm going to create a file for each select option in select box 'one'. Each file will have an array of values to put into select box 'two'.

Update: technically this isn't JSON, even though it works. More information here.

select_colours.js:
['red','orange','black','purple','yellow','forest green']

select_numbers.js:
['3242','84930','12','5433344','8837845','1980']

select_letters.js:
['G','f','s','j','P','m']

This example isn't using a lot of data, but chances are in real life, you wouldn't use Ajax unless you had a lot of extra data to get back from the server. Otherwise, it wouldn't be worth going to the server to get the data, and you might as well just put the data directly into the page.

JavaScript

Any usage of XMLHTTPRequest starts with a function similar to this. It finds the XMLHTTPRequest object in a way that works across all browsers, then it sets up a callback function to do the dirty work, and sends the request to a url:

function httpRequest(url, callback) {
    var httpObj = false;
    if (typeof XMLHttpRequest != 'undefined') {
        httpObj = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try{
            httpObj = new ActiveXObject('Msxml2.XMLHTTP');
        } catch(e) {
            try{
                httpObj = new ActiveXObject('iMicrosoft.XMLHTTP');
            } catch(e) {}
        }
    }
    if (!httpObj) return;

    httpObj.onreadystatechange = function() {
        if (httpObj.readyState == 4) { // when request is complete
            callback(httpObj.responseText);
        }
    };
    httpObj.open('GET', url, true);
    httpObj.send(null);
}

Now, we'll add three more JavaScript functions. First, we'll add a callback function to take our JSON data and put it into the select box:

function fillSelect(JSON) {
    var selectTwo = document.getElementById('two');
   	
    // clear out existing options
    while (selectTwo.options.length) {
        selectTwo.options[0] = null;
    }
	
    // fill with new options from JSON array
    var data = eval(JSON);
    for (var i=0;i < data.length;i++) {
        selectTwo.options[selectTwo.options.length] = new Option(data[i]);
    }
}

Notice we use the eval() function to turn our JSON text string into a real JavaScript object.

Next, we'll add an event handler function to react when the first select box changes. This will send off the actual XMLHTTPRequest:

function onSelectChange() {
    // get the value of the selected option in select box 'one'
    var selectOne = document.getElementById('one');
    var selectedOption = selectOne.options[selectOne.selectedIndex].value;

    if (selectedOption != "") {
        // find the appropriate javascript file
        httpRequest('select_' + selectedOption + '.js', fillSelect);
    } else {
        // empty the options from select box two
        fillSelect('[]');
    }
}

Lastly, we need to assign the onSelectChange() event handler to the select box. We'll do this in a window.onload function:

window.onload = function() {
    var selectOne = document.getElementById('one');
    selectOne.onchange = onSelectChange;
}

Conclusion

There you have it! If you want to see it in action, click on the files listed below:

Published on May 23rd, 2006. © Jesse Skinner

Java UI Toolkits (for the Web)

One thing that was big at JAX were these toolkits that allow Java developers to program user interfaces the way they're used to, by using libraries similar to SWT or Swing.

Two big ones I saw were Rich AJAX Platform (RAP), based on SWT, and wingS, based on Swing.

Now, Google has released the Google Web Toolkit (GWT). Not tightly based on a previous Java UI framework, GWT seems to be another good option for developing complex web user interfaces in Java.

These toolkits make things a lot easier for Java developers to make web user interfaces without having to master CSS and JavaScript. Java developers can stay in Java and have web interfaces generated for them. The result will be more rich web-based applications, something we will all benefit from.

Personally, I still have a lot of fun working with JavaScript and CSS by hand. I don't know if I'll ever start using one of these code-generating frameworks. I suspect those of us who have the patience and passion to put up with this stuff are in the minority.

Published on May 22nd, 2006. © Jesse Skinner

The Carnival of the Web

I'd like to announce The Carnival of the Web. This will be a monthly blog carnival showcasing the best posts in the wide world of web professionalism. The first carnival will take place on Sunday, June 18th, 2006.

This carnival will be aimed entirely at web professionals. These include web designers, web developers, web masters, search engine optimizers, or anyone else who works with or creates web sites. The posts can be about any topic of interest to web professionals. This includes web design, HTML, CSS, JavaScript, Ajax, SEO, usability, accessibility, web standards. General topics relating to the past, present or future state of the web will also be very welcome.

If you have a blog and would like to participate, please send in your submission!

Published on May 18th, 2006. © Jesse Skinner

Hire an Ajax Freelancer

If you want Ajax on your web site, I'm your man.

Although I'm already available to do all types of web freelancing, I want to emphasize that I specialize as an advanced JavaScript, CSS and Ajax freelancer. I've been doing Ajax and other advanced JavaScript for over two years now, and it's really my favourite thing to do.

If you're not really sure what is possible, I can also offer suggestions on ways to improve the usability of your site while still following best practices, web standards and accessibility guidelines.

So if you want to use some animation, auto-complete, XMLHttpRequest or any of that other Ajax stuff on your web site, or if you are a web developer or designer who needs help with JavaScript, please contact me.

Published on May 17th, 2006. © Jesse Skinner

Lend money to make money

There is a new online peer-to-peer loan concept that is growing, and I think it's a great idea. (Via slashdot). Two new companies, Prosper and Zopa, are allowing people to ask the public to lend them money. Anyone can bid on lending the money, stating their own interest rate. Whoever offers the lowest interest rate gets to lend the money (and make the interest).

The result? A pure capitalist financial system that doesn't involve banks. Anyone can get a loan, and anyone can make money by lending money. Everyone benefits.

This also reminds me of Kiva, a web site that lets people lend money to those in developing countries. I think this is a great alternative to just donating money since it helps build up the economy in these countries. It's very cool to see the idea being extended to the rest of the world.

Update: Only people in the US can use Prosper, and only people in the UK can use Zopa. I hope they (or others) make this available to the rest of us (specifically, Canadians living in Germany)!

Published on May 17th, 2006. © Jesse Skinner

Code Igniter

I'm absolutely in love. While I bored was at JAX, I searched around for a PHP framework like Ruby on Rails. I already knew about CakePHP, but I wasn't convinced. I looked at a few others, but nothing caught my eye. Then I discovered Code Igniter.

Code Igniter comes from the people who make Expression Engine. I had already heard great things about that, and I had even considered purchasing a license. Code Igniter, however, is free and open source. It's quite new (first beta was released in February) but it is incredibly professional and already very stable.

Code Igniter does absolutely everything I want it to, and nothing I don't want it to. It's incredibly simple and clean, so there are no surprises or weird tricks. It forces you to organize your code using an MVC structure (actually, a VC structure — using a model is optional). This keeps your code cleaner and easier to maintain. It also comes with a number of libraries that help with common web development things like email and uploaded files.

This weekend, I rewrote my whole custom-made blog code for this site. It only took about 4 or 5 hours, and it was actually fun to do. It also reduced the amount of code I had, and makes it much, much easier to maintain and change in the future. For example, until now I was too lazy to add contact pages properly, so I just added blog articles for Contact Me, etc. and pointed links at these. Now, I've changed the pages to use /contact/me and /contact/hire, and I could easily reuse my blog template. This change took about 10 minutes.

By default, URLs are of the form /class/function/parameters. But if you want to do something different (I use /blog/2006/5/article-name), you can set up routing rules for anything you want. Actually, Code Igniter is totally flexible to let you do whatever you want. Anytime I got stuck, I poked around in the documentation and found that there was something in place specifically for my problem.

Also wonderful: only the minimal amount of PHP is loaded to create each page. You can load classes globally, if you need them, but by default, you only load what you need when you need it. This keeps every page as fast as possible, something I was worried about with other frameworks like CakePHP.

Okay, that's enough ranting. If you use PHP, check out Code Igniter. There are some videos you can watch to see just how easy Code Igniter really is. The user guide is also a pleasant read and explains everything really well.

Published on May 14th, 2006. © Jesse Skinner

Back from JAX

I had a really nice time in Wiesbaden, Germany at JAX 2006. Apart from being in a gorgeous city, the conference had some interesting content. Most of it was about Java technologies and I won't bore you (and myself) with too much of that, but I also attended sessions on Ruby on Rails, Groovy and AJAX.

It was interesting to get a sense of where the industry is moving. Dynamic languages are becoming much more important, although I find "real" developers are hesitant to move in that direction. Personally, I love the concepts behind Groovy and Ruby. They speed up development and take away much of the painful grunt work involved in regular programming. They might be slower, but in the future as servers get faster, I don't think this will be such a problem.

Another striking trend was an overwhelming buzz and a sense of confusion and mystery around AJAX. Remember, this was a Java conference so many of the participants don't work directly on the web. Some only heard of AJAX for their first time at JAX. There seems to be a big divide between programmers and designers, and neither seems to understand advanced JavaScript programming. Programmers have avoided JavaScript, considering it a simple scripting language. Designers have avoided it for being a programming language. Now that some really sophisticated user interfaces are possible on the web, both sides are starting to get really excited.

Until now, I've totally hated the term AJAX. It's just a buzzword slapped on to something that JavaScript developers have been doing for years, and you know how much I hate buzzwords. Now, I see that it has helped to create awareness and get people excited about the possibilities in the browser. I don't think we will be using the term AJAX for many years, but at the moment it has gotten many people to take web applications more seriously and to start thinking about how they can improve the web. This is always a good thing.

Published on May 14th, 2006. © Jesse Skinner

See you at JAX 2006

From Tuesday (May 9th) until Thursday (May 11th), I'll be attending JAX 2006, a Java conference in Wiesbaden, Germany. Not only will I learn all about what's new in the Java world, I'll be able to really test out my knowledge of German. (Eek!)

If any of you are going to be there by some freak chance, let me know so we can meet up. For the rest of you, I'll be sure to write about anything that relates to web development and the future of the web.

Published on May 3rd, 2006. © Jesse Skinner