In this article we will use XMLHttpRequest
JavaScript object to send files to a server without page reloading. You will know how to build a file uploader form, how to handle file submitting, initiate a sending request, and handle uploading on a server side. Also, we will see how to do the same with several lines of code using Uploadcare services.
Jump right into the section you need:
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.
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.
It involves the following steps:
- Creating an HTML form.
- Creating an AJAX script (
XMLHttpRequest
object and handlers).
- Setting up a server-side PHP script to accept data from AJAX requests.
- Testing in a browser.
Without further introduction, let’s create an AJAX upload example.
Local htdocs folder for AJAX file uploader
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 Uploading</title>
</head>
<body>
<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="upload.js"></script>
</body>
</html>
The action
form points to a PHP script that processes 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.
Create an upload.js
file in your AJAX-test
project’s folder. Copy and paste this code:
var myForm = document.getElementById('formAjax');
var myFile = document.getElementById('fileAjax');
var statusP = document.getElementById('status');
myForm.onsubmit = function(event) {
event.preventDefault();
statusP.innerHTML = 'Uploading...';
var files = myFile.files;
var formData = new FormData();
var file = files[0];
formData.append('fileAjax', file, file.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadHandling.php', true);
xhr.onload = function () {
if (xhr.status == 200) {
statusP.innerHTML = 'Upload copmlete!';
} else {
statusP.innerHTML = 'Upload error. Try again.';
}
};
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 set up an AJAX request with the new XMLHttpRequest()
object, and open a POST connection to uploadHandling.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 uploadHandling.php
. And yes, you must still process the file on the backend, to which the AJAX request submits the file for processing.
Use this uploadHandling.php
script as a server-side solution for this AJAX file uploader.
$currentDir = getcwd();
$uploadDirectory = 'uploads/';
if (!empty($_FILES['fileAjax'] ?? null)) {
$fileName = $_FILES['fileAjax']['name'];
$fileTmpName = $_FILES['fileAjax']['tmp_name'];
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
if (isset($fileName)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo 'The file ' . basename($fileName) . ' has been uploaded.';
} else {
echo 'An error occurred while uploading. Try again.';
}
}
}
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.
Also, you may want to add a file validation. For example, if you want to accept images only, you may add the check like this:
$allowedFileExtensions = ['jpeg', 'jpg', 'png', 'gif'];
$fileType = $_FILES['fileAjax']['type'];
$fileExtension = strtolower(pathinfo($fileName,PATHINFO_EXTENSION));
if (! in_array($fileExtension, $allowedFileExtensions)) {
echo 'JPEG, JPG, PNG and GIF images are only supported';
}
It’s time to test our AJAX file uploader. Launch your index.html page in a web browser:
Local AJAX uploader preview
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 files to a specific size. Other options are name length, some meta 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.
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 files.
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 →
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 file uploading and offer more options.
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 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.
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.