PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Monitoring File Uploads using Ajax and PHP

Creating the File Upload Form

The next step is to create the file upload form, which simply consists of a standard HTML form that includes a file input. The JavaScript code we will develop later will create a hidden iframe that this form will submit to, however in order to keep this form accessible for users that don't have JavaScript enabled we don't need to include this iframe in this HTML document.

This code loads the prototype.js file, which is available for download from http://prototypejs.org. The version of Prototype used in this article 1.6.0. Additionally, the code loads FileUploader.js and upload.js which we will create later in this article.

We load the FileUploader.php in this file, allowing us to refer to the ID_KEY constant (which corresponds to APC_UPLOAD_PROGRESS). Obviously you could just hardcode this value – I've just done it this way to keep the code tidy with no "magic values".

Listing 11 The file upload form (index.php)
<?php
    require_once('FileUploader.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title>File Uploader</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <script type="text/javascript" src="prototype.js"></script>
        <script type="text/javascript" src="FileUploader.js"></script>
        <script type="text/javascript" src="upload.js"></script>
    </head>
    <body>
        <form method="post" action="upload.php" enctype="multipart/form-data" id="theForm">
            <div>
                <input type="hidden" name="<?php echo FileUploader::ID_KEY ?>" value="" />
                <input type="file" name="myFile" />
                <input type="submit" name="submit" value="Upload file..." />
            </div>
        </form>
 
        <div id="status" style="display: none">
            Upload status: #{complete}/#{total} (#{percent}%)
        </div>
    </body>
</html>

This HTML document is completed by the inclusion of a div called #status. This element is used to show the upload status data. At this stage it includes only placeholders for where the values will appear. We will use the Template class that comes with Prototype to insert the values into the placeholders. By default, we hide this element.

Note: In order to use the show() and hide() methods of Prototype we must hide the element using an inline style tag, rather than using a CSS rule such as #status { display : none; }. Alternatively, you could leave this element to be displayed then hide it once the page has loaded using JavaScript.

In This Article


Additional Files