Learn AJAX image uploads using PHP, JavaScript and HTML5

ajax image uploadAJAX, an acronym for Asynchronous JavaScript and XML, includes HTML, XML, JavaScript and often PHP to create client-side web applications that wow your users. Why is client side important? Because client-side really means faster load times, less back and forth between the server and the user’s PC which ultimately means better performance all round. Programming in AJAX therefore requires you to have some basic knowledge of the web development techniques that are included in AJAX. The Intro To AJAX With jQuery (Web Programming Made Easy) course will teach you to use the power of AJAX and JQuery to create dynamic web applications. The video based course will show you how to modify a web page using JQuery as well as how to send and receive data to the server. It also covers how to load external content and how to build search forms for your projects.

The following tutorial will show you how to create a form and then how to use that form to allow users to upload an image to the form. We will create a progress bar to monitor the image upload as well as showing the percentage uploaded. This tutorial uses the progress element available in HTML5 so it is designed for newer browser types. The tutorial uses HTML5, JavaScript, PHP and AJAX.

If you are new to HTML5, the HTML5 Beginners Crash Course uses over 46 lectures and 9.5 hours of video content to teach you HTML for newcomers, how to access HTML5, how to use geolocation and advanced forms as well as using the HTML5 canvas for drawing.

Create the Form in HTML5

We are starting with an empty HTML5 document.

<!DOCTYPE html>
<h2>AJAX Image Upload</h2>
<form id="image_upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="image1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>

We have added a heading for our page called “AJAX image upload”. We then created a form called “upload_form”. This is the form the user uses to upload the image. We add a file input type for our form to allow the user to browse the files on their computer. We have also included a button to allow the user to start the upload and we assign the uploadFile function to the button. We will be using JavaScript and AJAX to upload the file. Finally, we’re adding the progress bar element to represent the total uploaded as an upload bar that appears to animate automatically as the file uploads. The status and “loaded_n_total” also shows the user information about how far the upload has progressed.

For more information on working with HTML5 forms and elements, the Learn HTML5 & JavaScript course video tutorials on HTML5 and JavaScript covers basics as well as teaching you how to work with advanced techniques.

Add the JavaScript

First we create a script to get out elements from our page. Since this is something we do quite regularly, we will create a function that gets the elements and then merely access the function each time we want to get an element. Now when you want to access an element, all you need to type is _() and include the elementID within the brackets.

The function will look like this:

function _(elementID)
             return document.getElementById(elementID);

Then we are going to write the uploadFile function that we associated with our button in our form. This function will allow us to upload the file the user selects. The function uses the XMLHTTPRequest function to upload the data. The function also makes provision for a number of event listeners to upload the page data whilst we are waiting for the file upload to complete. It also uses four functions to update the page data depending on the progress or completion or failure of the file upload. Finally, it uses PHP to upload the file to the server using the AJAX.send method.

The uploadFile function code looks like this:

function uploadFile()
              var file = _("image1").files[0];
              formdata.append("file1", file);
              var ajax = new XMLHttpRequest();
             ajax.upload.addEventListener("progress", myProgressHandler, false);
              ajax.addEventListener("load", myCompleteHandler, false);
              ajax.addEventListener("error", myErrorHandler, false);
              ajax.addEventListener("abort", myAbortHandler, false);
              ajax.open("POST", "file_upload_parser.php"); ajax.send(formdata);

The Learn HTML5, CSS, PHP, MySQL, jQuery & AJAX in one project course teaches you how to create dynamic database driven websites that allow for client-side updating using CSS, PHP, HTML5, MySQL, AJAX and JQuery. The course will teach you how to build full-featured, functional websites using the above technologies. How to install and configure PHP and MySQL, and how to use PHP and MySQL as the backend of your website whilst using CSS, AJAX and JavaScript to create beautiful user interfaces for those sites.

Add the Event Handler Code

Now you need to write the code for the various event listeners we have created in the above code. We need to write code to handle the updating of the progress bar. We also need to add code to show the upload is successful, or that it failed, or that the upload was aborted.

The code for the functions will look like this:

function myProgressHandler(event)
           _("loaded_n_total").innerHTML =
                     "Uploaded "+event.loaded+" bytes of "+event.total;
                      var percent = (event.loaded / event.total) * 100;
           _("progressBar").value = Math.round(percent);
           _("status").innerHTML = Math.round(percent)+"% uploaded...
                                                        please wait";
function myCompleteHandler(event)
           _("status").innerHTML = event.target.responseText;
           _("progressBar").value = 0;
function myErrorHandler(event)
           _("status").innerHTML = "Upload Failed";
function myAbortHandler(event)
          _("status").innerHTML = "Upload Aborted";

Add the PHP code

Finally we need to write the PHP code to allow the file to be uploaded to the server

The file will look like this:

$fileName = $_FILES["image1"]["name"]; // The file name
$fileTmpLoc = $_FILES["image1"]["tmp_name"];
$fileType = $_FILES["image1"]["type"];
$fileSize = $_FILES["image1"]["size"];
$fileErrorMsg = $_FILES["image1"]["error"];
if (!$fileTmpLoc)
    if file not chosen echo "ERROR: Please browse for a file before clicking
    the upload button."; exit(); }
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName"))
                   { echo "$fileName upload is complete"; }
                   { echo "move_uploaded_file function failed"; }

AJAX Image Upload

You now have an idea about how HTML5, AJAX, JavaScript and PHP work together to upload images. The Ajax, jQuery and JSON for Beginning Web Developers will teach you the technologies you need to become a web programmer. The course teaches you by showing you how to create real projects. The three hours of video content and 18 lectures are designed to teach you what AJAX, JQuery and JSON are and how they work together using real world examples.