How-Tos March 18, 2020 by Mikhail Kokarev

AJAX Image File Upload: The Shortest Script

Sometimes, file uploaders may take a while to reload a whole page, send requests to a server, wait for the responses, and then wait for the entire page to refresh on the client side.

AJAX, short for Asynchronous JavaScript and XML, is a well-known technique for creating better UX with much faster responses from the webserver. It provides immediate updates to active elements only, without reloading the whole HTML page. One of the best examples of AJAX in action is when you start typing in a search field, and it suggests similar results in a popup.

With AJAX, you can upload files faster as well. One example is image uploading, and we’ll be taking a closer look at that in this article. However, you can also adapt the script for general file uploading in no time.

Ways of Implementing AJAX File Uploaders

This article shows two ways of implementing an AJAX file uploader.

  • JavaScript and PHP uploader
  • Automated Uploadcare AJAX uploader

The first way includes server PHP and JS scripts, while the second one includes just simple HTML instructions. The complexity of these solutions ranges from one page of code to just a few lines, respectively.

Prerequisites

To follow along with this tutorial, you need to have a web development environment set up on your computer. That includes a server (Apache or Nginx) with PHP support. Use a code editor or IDE of your choice, like Visual Studio Code, which is our preferred solution at Uploadcare.

The difficulty is moderately easy, and this article is aimed at beginner developers or those who want to optimize their processes.

Creating an AJAX Image File Uploader with JS and PHP

It involves the following steps:

  1. Creating an HTML form.
  2. Creating an AJAX script (XMLHttpRequest object and handlers).
  3. Setting up a server-side PHP script to accept data from AJAX requests.
  4. Testing in a browser.

Without further introduction, let’s create an AJAX upload example.

macOS Finder window, htdocs folder with AJAX upload website containing HTML, JS and PHP

Step 1. Creating an HTML form

Create a folder for the project (e.g., AJAX-upload) in your website’s root directory ( (usually it’ll be something like public_html, htdocs, or www), and then create a new index.html file there.

Copy & paste the following file-uploading code into your newly created file. It is a straightforward form with a file select input and a submit button:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>AJAX Image Uploading</title>
</head>
<body>
    <p>Image uploader</p>
    <form id="formAjax" action="uploadHandling.php" method="POST">
        <input type="file" id="fileAjax" name="fileAjax" /><br /><br />
        <input type="submit" id="submit" name="submit" value="Upload" />
    </form>
    <p id="status"></p>
    <script type="text/javascript" src="imageUpload.js"></script>
</body>
</html>

The action form points to a PHP script that processes image file uploading. The method of sending data to a server is POST.

In this form, we don’t need to specify the enctype attribute, because it’s only required for text input management (e.g., replacing blank spaces with ‘+’ symbols before sending the string via POST to the server).

Also, we need to set an id for the input fields, because we’ll refer to this in our AJAX script. Even though we’re pointing the form’s action to the PHP script, we’ll also create a JavaScript that will intercept form submissions and provide asynchronous feedback.

Step 2. Creating an AJAX script

Create an imageUpload.js file in your AJAX-test project’s folder. Copy and paste this code:

var myForm = document.getElementById('formAjax');  // Our HTML form's ID
var myFile = document.getElementById('fileAjax');  // Our HTML files' ID
var statusP = document.getElementById('status');

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

    statusP.innerHTML = 'Uploading...';

    // Get the files from the form input
    var files = myFile.files;

    // Create a FormData object
    var formData = new FormData();

    // Select only the first file from the input array
    var file = files[0]; 

    // Check the file type
    if (!file.type.match('image.*')) {
        statusP.innerHTML = 'The file selected is not an image.';
        return;
    }

    // Add the file to the AJAX request
    formData.append('fileAjax', file, file.name);

    // Set up the request
    var xhr = new XMLHttpRequest();

    // Open the connection
    xhr.open('POST', '/uploadHandling.php', true);

    // Set up a handler for when the task for the request is complete
    xhr.onload = function () {
      if (xhr.status == 200) {
        statusP.innerHTML = 'Upload copmlete!';
      } else {
        statusP.innerHTML = 'Upload error. Try again.';
      }
    };

    // Send the data.
    xhr.send(formData);
}

The script starts by saving all the form elements and status into the respective variables using this DOM’s method: .getElementById(name).

Then add the .onsubmit event handler, which is the main function in this script, since it waits for a user to submit the form.

Define a form object and add a simple validation step to check if the file type is an image.

Set up an AJAX request with the new XMLHttpRequest() object, and open a POST connection to imageUpload.php. The backend script will take care of further file processing.

Going back to the current script, set up an .onload event listener for the xhr object, so it’ll notify the user on the HTML page about the uploading outcome. Status 200 means that everything is OK.

Here, you’re making a post request to imageUpload.php. And yes, you must still process the file on the backend, to which the AJAX request submits the file for processing.

Step 3. Setting up a server PHP script to accept data from the AJAX request

Use this uploadHandling.php script as a server-side solution for this AJAX image uploader.

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

    // Store all errors
    $errors = [];

    // Define available file extensions
    $fileExtensions = ['jpeg','jpg','png','gif'];

   //if(!empty($_POST['fileAjax']) || $_FILES['image']) {
        $fileName = $_FILES['myFile']['name'];
        $fileTmpName  = $_FILES['myFile']['tmp_name'];
        $fileType = $_FILES['myFile']['type'];
        $fileExtension = strtolower(pathinfo($fileName,PATHINFO_EXTENSION));

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

        //echo $uploadPath;

        if (isset($fileName)) {
            if (! in_array($fileExtension,$fileExtensions)) {
                $errors[] = "JPEG, JPG, PNG and GIF images are only supported";
            }
            if (empty($errors)) {
                $didUpload = move_uploaded_file($fileTmpName, $uploadPath);
                if ($didUpload) {
                    echo "The image " . basename($fileName) . " has been uploaded.";
                } else {
                    echo "An error occurred while uploading. Try again.";
                }
            } else {
                foreach ($errors as $error) {
                    echo $error . "The following error occured: " . "\n";
                }
            }
        }
    //}
}
?>

This script executes a pretty straightforward process of handling uploaded files and putting them into the upload folder that you specify at the beginning of the script. Feel free to edit the error messages that’ll be shown to the user.

Step 4. Testing in a browser

It’s time to test our AJAX image uploader. Launch your index.html page in a web browser:

Safari window; header: Image uploader; buttons: Choose file, Upload.

If everything works correctly, you can add more methods to validate the incoming files, such as a file size check, which can limit the uploaded images to a specific size. Other options are name length, some meta image parameters, etc.

This article provides a very basic solution. If you want to use it on real systems, look into additional security concerns, because you’re essentially giving random web surfers an opportunity to upload files directly to your server.

Automated AJAX File Upload with Uploadcare

Uploadcare uses asynchronous uploading techniques like in the scripts that we created earlier. However, you don’t need to bother with JS/PHP, because the service will take care of file uploading from start to finish. It offers the quickest, most optimal and secure way of uploading images.

How to access Uploadcare

Install the Uploadcare widget from the CDN by including this snippet within the head element of your HTML webpage:

<script>UPLOADCARE_PUBLIC_KEY = "YOUR_PUBLIC_KEY";</script>
<script src="https://ucarecdn.com/libs/widget/3.x/uploadcare.full.min.js" charset="utf-8"></script> 

There is an NPM install option as well. Type this in your command line, and the Uploadcare widget will be available to use in your project:

npm install uploadcare-widget

Importing is pretty simple too:

import uploadcare from 'uploadcare-widget'

By default, 'uploadcare.js' is used. Still, you can choose to import a certain bundle, for example, uploadcare-widget/uploadcare.full.min.js See more widget bundles →

HTML file upload code

After the widget is available, you can use it in the body of your webpage. For example, in a form element, include this input field:

<input type="hidden" role="uploadcare-uploader" name="my_file" />

And you will see the button appear. It’ll take care of image uploading and offer more options.

Should I Create My Own Uploader or Use Uploadcare?

The scripts above are just the bare bones of the AJAX file uploading technology, so we urge you not to use them on real projects without major improvements.

Providing a reliable and convenient file/image loader on your website is not as simple as it might seem at first glance. Writing an AJAX script and customizing it for your needs requires PHP and JS knowledge; plus, the developer has to foresee possible security breaches and include defense mechanisms in the code. It might take weeks or months just to perfect this one feature for your business.

Allow your customers to upload files from their devices and social media via secure, UX-friendly, and highly-customizable widget.

An out-of-the-box file uploader solution (like Uploadcare) is a great choice because it takes care of security, sustainability, etc. It works for small and medium businesses and enterprises by providing various feature sets and pricing models.

Leave a comment

*

*