File Upload with AJAX: A Quick Guide

June 24th, 2022

Our guest blogger, Gilad David Maayan, provides us a quick way on how to implement a file upload with AJAX

Image Source - Free Stock photos by Vecteezy

What is AJAX?

Asynchronous JavaScript and XML (AJAX) is a technique for creating faster interactive web apps. It combines multiple programming tools, such as JavaScript, Extensible Markup Language (XML), and dynamic HTML (DHTML).

AJAX is based on open standards. It uses a browser with built-in XMLHttpRequest object, JavaScript and HTML Document Object Model (DOM) to exchange data between a web server and a web browser and display the data.

This data exchange process works behind the scenes to enable web pages to update asynchronously. As a result, you can update parts of a webpage and quickly display the results to the user—there is no need to wait to reload an entire page.

File Uploading with AJAX

Most websites need to collect files from users, typically file upload forms. These forms should be user-friendly to facilitate fast and easy uploads. Job applications, for example, require file upload forms to enable applicants to upload their information. File uploading processes enable sites to accept and manage user files, including images, PDFs, and videos.

AJAX file uploads can help make a file uploader fast, offering a positive user experience. It speeds up the process by updating content asynchronously. As a result, there is no need to reload an entire page, then send requests to the server, then wait for a response, and finally wait for the whole page to refresh. Instead, AJAX reloads only the required parts of a page to instantly inform users on whether the files were uploaded or if there was an issue and the file did not upload because it is too large, for example.

Quick Tutorial: Creating an AJAX Image File Uploader with JS and PHP

Step 1: Creating an HTML Form

Create a folder for the project in your website’s root directory, and create a new index.html file there. In the <body> element of your index file, add this simple form:

<form id="myAjaxForm" action="uploader.php" method="POST">
    <input type="file" id="fileForUpload" name="fileForUpload" /><br /><br />
    <input type="submit" id="submit" name="submit" value="Upload" />
</form>

A few important points about this code:

Below it, we’ll add an empty <p> element which we can use to display the status of the upload process:

<p id="uploadStatus"></p>

Lastly, we’ll add a reference to the AJAX script that will handle the file upload process (see the following section):

<script type="text/javascript" src="fileUpload.js"></script>

Step 2: Creating the AJAX Script

Now, we’ll create a fileUpload.js file in the project folder. Let’s go through the code bit by bit.

First, we declare three variables and use them to pull the form, file, and status field from our HTML:

    var uploadForm = document.getElementById('myAjaxForm');
    var uploadFile = document.getElementById('fileForUpload');
    var uploadStatus = document.getElementById('uploadStatus');

Next, we use the .onsubmit event handler to trigger this script when a user submits the form.

The preventDefault() function ensures that the form does not perform its default action, allowing us to define a custom action via AJAX.

    uploadForm.onsubmit = function (event) {
        event.preventDefault();

Now we load the file uploaded by the user. For simplicity, we’ll take only the first file, by accessing the first element in the files array. You can expand this script to handle multiple file upload.

    var file = uploadFile.files[0];

It’s time to work some AJAX magic. Let’s create a formData object, which lets you send key/value pairs to an XMLHttpRequest. We use this object to send form data asynchronously via AJAX.

The code below creates a formData object and populates it with the file the user uploaded:

    var formData = new FormData();
    formData.append('fileForUpload', file, file.name);

Now, this code creates an XMLHttpRequest and opens a connection. We specify the name of the PHP script, uploader.php, which you can see in the following section:

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/uploader.php', true);

The following handler checks the status of our request and updates the status element accordingly. If the HTTP status is 200 = OK, the upload is deemed to have completed successfully:

    xhr.onload = function () {
        if (xhr.status == 200) {
            uploadStatus.innerHTML = 'Upload finished successfully!';
        } else {
            uploadStatus.innerHTML = 'We’re so sorry. The upload failed.';
        }
    };

Finally, this command sends the data to the server:

    xhr.send(formData);
}

Remember that this script won’t work without the server side element to process the uploaded files. We’ll show how to build the PHP script in the following section.

Step 3: Creating the Server-Side PHP Script

Use the following code as the PHP script. It must be named uploader.php so it can be referenced correctly from the HTML and JavaScript we showed above.

This is a standard file upload script that grabs the input file provided by the user and places it in the specified directory — userFileUploads. If an error occurred, it displays an error message and details of the error.

<?php
    $currentDir = getcwd();
    $uploadDirectory = "userFileUploads/";

   $errors = [];

  if(!empty($_FILES['fileForUpload'] ?? null)) {
        $fileName = $_FILES['fileForUpload']['name'];
        $fileTmpName  = $_FILES['fileForUpload']['tmp_name'];
        $fileType = $_FILES['fileForUpload']['type'];

       $uploadPath = $currentDir . $uploadDirectory . basename($fileName);

       if (isset($fileName)) {
            if (empty($errors)) {
                $didUpload = move_uploaded_file($fileTmpName$uploadPath);
                if ($didUpload) {
                    echo "The file " . basename($fileName. " was uploaded successfully.";
                } else {
                    echo "Sorry, an error occurred. File upload failed.";
                }
            } else {
                foreach ($errors as $error) {
                    echo $error . "Error details: " . "\n";
                }
            }
        }
    }
?>

Step 4: Expanding the Script

Above we showed a very basic Ajax file upload mechanism. As you get the hang of AJAX file upload, you can expand these scripts by adding more functionality:

Conclusion

In this article, I explained the basics of file upload with AJAX, and showed how to write your own AJAX file upload script in four steps:

  1. Creating an HTML form, where the action of the form references the PHP file that will process uploads.
  2. Creating an AJAX script that creates a formData object and populates it with the file the user uploaded.
  3. Creating a server-side PHP script - you can start with a basic script that grabs the input file provided by the user and places it in the specified directory.
  4. Expanding the script - it is a good idea to add more features to your script such as file validation and integration with cloud storage.

I hope this will be useful as you add file upload functionality to your web applications.