3 Steps Simple Image Upload Using AJAX PHP

Welcome to a tutorial and example of how to upload an image using AJAX and PHP. The Stone Age of the Internet is long over, and gone are the days where we have to reload the entire page to submit a form.

There are 3 main components to an AJAX-PHP image upload:

  1. An HTML file upload form.
  2. Javascript to manage the AJAX image file uploads.
  3. Server-side PHP script to check and process the image upload.

Let us walk through a simple example in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes AJAX Upload Useful Bits & Links
Tutorial Video The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

  • Access 1-upload-form.html in the browser.
  • Captain Obvious – Use http:// and not file://.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

AJAX IMAGE UPLOADER

All right, let us now get started with the AJAX image uploader.

 

STEP 1) HTML IMAGE UPLOAD FORM

1-upload-form.html
<!-- (A) UPLOAD FORM -->
<form id="upform" onsubmit="return ajaxup.add();">
  <h1>AJAX Upload Demo</h1>
  <label for="upfile">Choose an image file:</label>
  <input type="file" accept=".png,.gif,.jpg,.webp" id="upfile" multiple required/>
  <input type="submit" value="Upload"/>
</form>
 
<!-- (B) UPLOAD STATUS -->
<div id="upstat"></div>

  1. No nasty surprises here, this is just a regular Joe HTML form with a single <input type="file"/> field.
  2. Also, take note of <div id="upstat">, we will be using this to show the status of the uploaded files.

 

 

STEP 2) JAVASCRIPT AJAX UPLOAD

2-ajax-upload.js
var ajaxup = {
  // (A) ADD TO UPLOAD QUEUE
  queue : [], // upload queue
  add : function () { 
    for (let f of document.getElementById("upfile").files) {
      ajaxup.queue.push(f);
    }
    document.getElementById("upform").reset();
    if (!ajaxup.uploading) { ajaxup.go(); }
    return false;
  },
 
  // (B) AJAX UPLOAD
  uploading : false, // upload in progress
  go : function () { 
    // (B1) UPLOAD ALREADY IN PROGRESS
    ajaxup.uploading = true;
 
    // (B2) FILE TO UPLOAD
    var data = new FormData();
    data.append("upfile", ajaxup.queue[0]);
    // APPEND MORE VARIABLES IF YOU WANT
    // data.append("KEY", "VALUE");
 
    // (B3) AJAX REQUEST
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "3-ajax-upload.php");
    xhr.onload = function(){
      // (B4) SHOW UPLOAD RESULTS
      document.getElementById("upstat").innerHTML += `<div>${ajaxup.queue[0].name} - ${this.response}</div>`;
 
      // (B5) NEXT FILE
      ajaxup.queue.shift();
      if (ajaxup.queue.length!=0) { ajaxup.go(); }
      else { ajaxup.uploading = false; }
    };
 
    // (B6) GO!
    xhr.send(data);
  }
};

This looks confusing at first, but keep calm and look carefully.

  1. When the HTML form is submitted, ajaxup.add() will fire up. This basically gets the selected files and appends them into the upload queue ajaxup.queue.
  2. ajaxup.go() is the actual function that does the AJAX upload.
    • It simply uploads the first file in the queue ajaxup.queue[0].
    • On upload completion, the file is removed from the queue ajaxup.queue.shift().
    • The next “upload cycle” then continues until the upload queue is exhausted – if (ajaxup.queue.length!=0) { ajaxup.go(); }

In short, all the Javascript does is upload one file at a time to prevent a server flood.

 

 

STEP 3) PHP IMAGE UPLOAD HANDLER

3-ajax-upload.php
<?php
// (A) FILE CHECK
$result = "";
if (!isset($_FILES['upfile']['tmp_name'])) {
  $result = "No file uploaded.";
}

// (B) IS THIS A VALID IMAGE?
if ($result=="") {
  $allowed = ["bmp", "gif", "jpg", "jpeg", "png", "webp"];
  $ext = strtolower(pathinfo($_FILES["upfile"]["name"], PATHINFO_EXTENSION));
  if (!in_array($ext, $allowed)) {
    $result = "$ext file type not allowed - " . $_FILES["upfile"]["name"];
  }
}

// (C) MOVE UPLOADED FILE OUT OF TEMP FOLDER
if ($result=="") {
  $source = $_FILES["upfile"]["tmp_name"];
  $destination = $_FILES["upfile"]["name"];
  move_uploaded_file($source, $destination);
}
 
// (D) SERVER RESPONSE
echo $result=="" ? "OK" : $result ;

No BS here either, things are straightforward as well.

  1. Checks if a file is actually uploaded.
  2. Check if the uploaded file is an accepted image format.
  3. Move the uploaded image file out of the temporary folder.

 

 

USEFUL BITS & LINKS

That’s all for this project, and here is a small section on some extras that may be useful to you.

 

ALLOW ONLY A SINGLE UPLOAD

  • Just remove the multiple attribute – <input type="file" accept=".png,.gif,.jpg,.webp" id="upfile" required/>.
  • Hide the upload form on upload start – document.getElementById("upform").style.display = "none"
  • Best that you show some sort of upload progress though…
  • Do whatever you need on upload complete – Enable the upload form again, show a “thank you”, or redirect the user to another page.

 

SET THE IMAGE TYPE RESTRICTIONS

Yes, there are a ton of different image formats. If you want to change the accepted image formats, set the accept="EXTENSIONS" in the HTML. Also, remember to update 3-ajax-upload.php accordingly – $allowed = [EXTENSIONS].

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEATSHEET

PHP AJAX Image Upload (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *