So… you want to know how to upload a file via AJAX using jQuery and HTML5? Well, here’s how I’m doing it. This is not polished code, but something I cobbled together after visiting a number of sites and reading documentation in two books I have. I’m not going to provide the complete example or the PHP/server side of things, but this should be useful nonetheless.

Starting with HTML, I used the standard file input type with an onchange handler like so:

<input type="file" onchange="uploadIt(this.files);" name="uploadfile" id="uploadfile">
<div id="progressbox" >
<div id="progressbar"></div >
<div id="statustxt">0%</div>
<div id="output"</div>

The name of the field is completely arbitrary, and ultimately doesn’t matter because this field will not be submitted with your form, if you even have a form. If you do have a form, use an onsubmit() handler or your validation check to disable this field so the file isn’t uploaded a second time. By using the onchange handler, as soon as a file is chosen with the file dialog box, the upload process begins. No extra clicks are necessary. The progressbar and statustxt divisions (div) are used to indicate the upload progress, and the output division can be used for whatever output you want; while developing this code, I used it to report error messages and final status from the server.

The uploadIt function looks like this:

function uploadIt(files)
var file = files[0];
 case 'image/png': 
 case 'image/gif': 
 case 'image/jpeg': 
 case 'image/pjpeg':
 case 'image/webp':
 var fd = new FormData();
 url: '/upload-handler',
 type: 'POST',
 cache: false,
 contentType: false,
 processData: false,
 data: fd,
 success: function(data, textStatus, jqXHR)
 if( typeof data.error == 'undefined')
 $('#output').html('<b>success!:</b> ' +data);
 error: function(jqXHR,textStatus,errorThrown)
 $('#output').html('<b>error:</b> ' + errorThrown);
 xhr: function() {
 var myXhr = $.ajaxSettings.xhr();
 if(myXhr.upload) {
 var percentComplete = (event.loaded / * 100.0;
 $('#progressbar').width(percentComplete.toFixed(2) + '%') //update progressbar percent complete
 $('#statustxt').html(percentComplete.toFixed(2) + '%'); //update status text
 $('#statustxt').css('color','#000'); //change status text to white after 50%
 return myXhr;

In my particular implementation, I only wanted certain file types (png, gif, jpeg, and webp as determined by the browser) to be uploaded to the server. You could also check to make sure the file is greater than 0 bytes and less than an arbitrary limit here, but I don’t have that implemented here.

Every time we have a file of the corresponding type selected, the statustxt content is set to “0%”, then we create the FormData object that will do the important job of properly formatting the file for upload. In the fd.append() call, the first parameter is the field name as it will be received on the server; this is the reason why it’s not important to have the field name set in the input tag itself. Naturally, you could copy that or use the same one, but you could just as easily set it here or make this a variable set by jQuery through another AJAX call. In PHP, this is the field name that will appear in your $_FILES variable, so you will need to know what to look for.

Next we have the file variable. While the function received an argument called “files“, and you can handle multiple files through this functionality, I wanted to maintain clarity here, and only took the first file in the files array to process and upload. Looping through the contents of files would be trivial to get this to work for multiple uploads.

The last field in fd.append() is the file name as it existed on disk at the time the file was chosen. Using this field triggers FormData to use the Content-Disposition header which, from my experience, makes the upload possible.

Next, we use jQuery to initiate the upload via the ajax function. This is where things get ugly fast, but the bottom line is you can pretty much copy and paste what I have here. But for clarity’s sake, here’s what’s what:

url is the URL to which the file will be uploaded.

type is going to be POST, though you could also use PUT in theory. There’s no reason to use PUT, but you theoretically could.

cache just as a precaution, lets make sure the browser doesn’t cache anything.

contentType is going to get set by FormData a little bit lower, so don’t manually set it. Do not confuse this with the file’s actual type or MIME type! This will get set to something akin to “multipart/form-data”.

processData we’re not going to process the data locally, so move on.

data is the FormData object, fd, that contains our file.

Next up we have 3 anonymous functions that override the success, error, and xhr handlers in the jQuery ajax call. If you don’t care about displaying progress information as the file gets uploaded, you can omit the xhr handler, though you should keep success and error so your application will know if the upload succeeded or not.

The success and error handlers here are fairly simple, they really just give you an idea of what’s happened. The success function is called if there were no errors uploading the file on the client/browser side. I repeat, the success function is called if there were no errors uploading the file on the client/browser side of things. This means that as far as the browser knows, everything went smoothly, but it’s still entirely possible that there was some error on the server, such as the server being out of space, a virus scanner might have decided the file was malware, or even just a configuration problem. Personally, I beat my head against a server side problem for a couple of hours when I couldn’t figure out why files larger than 2 MB were failing even though I had PHP configured to accept files as large as 50 MB. (Spoiler: there was a typo in a different setting in my php.ini file, which caused PHP’s ini parser to stop and use default values..)

The error function is called if there was a javascript or browser error. As stated above, this does not handle errors on the server.

The xhr handler, as presented here, is responsible for updating the progress divisions, and thus the user. xhr is shorthand for XMLHttpRequest, and we need to send jQuery a lightly prepared version of the object prior to letting it do its thing, so we’re overriding its internal instantiator for the XMLHttpRequest object. First things first, we get the copy of XMLHttpRequest this particular call is going to use through the $.ajaxSettings.xhr() call. After making sure it has the upload member, we add an event listener with another anonymous function to handle the “progress” events. With the event argument, we calculate the completion percentage percentComplete, and use that to update the status indicators.

Assuming nothing has fundamentally changed by the time you read this, your script should be able to upload a file via AJAX using jQuery and HTML5 without submitting the whole form. (Assuming you bother with one at all.)

Although I’m a couple weeks behind on this, I thought I’d note that I fixed the cookie parsing in the HTTP add-on in Themis, and cookie handling is probably working better than ever at the moment. This isn’t to say I’m done with it; I need to go back in and fix a few curious issues with non-standard dates, empty cookie values, and restricting the maximum length of both a cookie name and value, but I can say that it’s significantly better than it was. I’m also considering moving the cookie system into a plug-in of its own; which it originally was.

The reason is that while cookies are only sent over HTTP connections, Javascript can initiate HTTP connections and manipulate cookies as well. This can be somewhat dangerous, and PHP along with other web scripting languages have [relatively] recently started adding a new optional flag to mark cookies as HTTP only to their headers. While I’ve added support for this to the cookie system in Themis, it’s somewhat meaningless at the moment: there’s an old Javascript implementation in the source tree, but it’s completely unused at the moment and isn’t attached in any way to the Themis DOM system. However, once we have a renderer, and Mark is working on that currently, then we will start to need a Javascript interpreter, and that in turn will lead back to proper cookie handling.

In addition, I’m now faced with adding configuration options for the cookie system, and it would be easier to manipulate those settings in the preferences window if the cookie system was in its own separate plug-in. This isn’t going to happen tomorrow, so don’t worry about it right now, but this is going to be a change in the future.

On other subjects, thinking about Javascript has got me wondering if Themis should use the binaries that are currently in the repository, try to get updated versions compiled, try to use a different existing Javascript implementation, or write our own. I had hoped to use V8 from Google’s Chrome, but it requires GCC 4 which isn’t available on BeOS though it is available on Haiku, but I haven’t managed to get it compiled due to a series of oversights within the Haiku community. I’m not going to put blame on any one person or organization, but I will say that getting scons working seems to be impossible on Haiku, so I can’t even test V8 at this point. Also, since the Themis project is about learning browser design, I’m leaning heavily on the “write our own” side of things now, though it would probably take years to get a version that’s as complete as today’s Javascript demands, and then I’d be playing catch up forever. Still, that’s on my mind…