How to Upload a File using PHP & Ajax

This post will show you how to upload a file using PHP & Ajax. File handling can sometimes require unique solutions. The conventional way of file upload is using a <form> tag. This solution works for many cases. But you might need to add some innovation when you need to upload without the form tag to avoid submitting the form.

Practically speaking –

There are some points where submitting a form might not be useful. For example, you can be working on a products page. And, you want to give the user the option to upload and delete the product images. So, in this case, you do not want the form to submit. But, at the same time, you would want to update the images.

Upload a file the normal way

Normally, when uploading a file or image through HTML, the code looks something like this:

<form method="post" action="upload.php" enctype="multipart/form-data" id="imageForm">
    <label> Please upload here: </label>
    <input type="file" name="image" accept="image/*" id="imageButton"/>
    <br>
    <input type="submit" name="submit" value="Upload">
<form>

And the PHP file for the above codes looks something like this:

<?php
$src = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
$output_dir = "images/".$filename;
if (move_uploaded_file($src, $output_dir )) {
        echo "Success! Image uploaded! File: ".$filename;
} else{
    echo "Error! Image upload failed! File: ".$filename;
};
echo "<br>";

This code works completely fine for most cases. The code above allows the user to select an image file and upload it to a server. And the PHP code captures the images and stores them in the images folder.

Upload a file without submitting a form

JavaScript offers a neat solution using FormData(). JavaScript allows the user to simulate the functionality of a <form> tag through FormData(). This allows any <input> file tag to be used without a <form> tag. We will make the AJAX call on the onchange event of the #imageButton element for this post.

First, we make a function and the FormData() object, which stores the image data from the user.

$('#imageButton').change(function(){
    // Making the image file object
    var file = $('#imageButton').prop("files")[0];

    // Making the form object
    var form = new FormData();

    // Adding the image to the form
    form.append("image", file);

    // AJAX Call goes here, keep reading
});

The variable form represents an object of FormData() And it simulates a <form> tag. The data is stored in key-value pairs as well.

FormData() has some useful functions as well, such as append(), delete(), get(), has(), set()and a few more. Furthermore, FormData() has fairly decent support.

The AJAX

Now it’s time to call the AJAX. This is quite similar to your normal AJAX call, but with a few additions.

$('#imageButton').change(function(){
    // Making the image file object
    var file = $('#imageButton').prop("files")[0];

    // Making the form object
    var form = new FormData();

    // Adding the image to the form
    form.append("image", file);

    // The AJAX call
    $.ajax({
        url: "upload.php",
        type: "POST",
        data:  form,
        contentType: false,
        processData:false,
        success: function(result){
            document.write(result);
        }
    });
});

The most important bits here are:

  • processData: false
  • contentType: false.

The processData argument tells the browser not to convert the object data into url-encoded string.

The contentType: false tells the server that the upcoming data is not a string.

You can also set this option to be multipart/form-data. But false is usually better since data may also be a mix of images and strings. The URL is the URL where the request is sent. type is the type of request, e.g. GET, POST, PUT. The Success argument is a function to be executed once the request is successful.

You can read more about the AJAX function on the jQuery website.

The PHP

The PHP remains the same.

Uploading multiple files

Code for multiple files is quite similar as well, with minor modifications.

HTML and JS

In the <input> tag, an attribute multiple is added. The name attribute is also slightly changed and [] is added. This indicates multiple values.

<input type="file" name="image[]" accept="image/*" id="imageButton" multiple/>

In JavaScript, you need to add the complete files array instead of one file object like so:

var file = $('#imageButton').prop("files");

And while appending, use [] in the key name:

form.append("image[]", file);

PHP

On the server side, there is only one modification, i.e., code is in a loop.

<?php
$len = count($_FILES['image']);

for($i = 0; $i < $len; $i++){
    $src = $_FILES['image']['tmp_name'][$i];
    $filename = $_FILES['image']['name'][$i];
    $output_dir = "images/".$filename;
    if(move_uploaded_file($src, $output_dir )){
        echo "Success! Image uploaded! File: ".$filename;
    }else{
        echo "Error! Image upload failed! File: ".$filename;
    };
    echo "<br>";
}

Wrapping up

Formdata() and AJAX together can be very powerful. These can also be used to transfer multiple data types, web scrapping, improving site security, and much more! Check out the links below to learn more:

Now you know how to upload a file using PHP & Ajax. You may also want to read “how to enable ZipArchive for PHP” if you plan to upload Zip files.

The complete code to upload using PHP and AJAX

HTML/JS:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>FormData - AJAX File Upload</title>
</head>
<body>
    <label> Please upload here: </label>
<!-- For Single File: -->
    <input type="file" name="image" accept="image/*" id="imageButton"/>
<!-- For Multiple Files: -->
<!-- <input type="file" name="image[]" accept="image/*" id="imageButton" multiple/> -->
    <script>
       $('#imageButton').change(function(){
            // Making the image file object
            var file = $('#imageButton').prop("files")[0];
            // For Multiple Files:
            // var file = $('#imageButton').prop("files");
            // Making the form object
            var form = new FormData();
            // Adding the image to the form
            form.append("image", file);
            // form.append("image[]", file) // for multiple files
            // The AJAX call
            $.ajax({
                url: "upload.php",
                type: "POST",qq
                data:  form,
                contentType: false,
                processData:false,
                success: function(result){
                    document.write(result);
                }
            });
        });
    </script>
</body>
</html>

PHP:

<?php
$len = count($_FILES['image']);
for($i = 0; $i < $len; $i++){
    $src = $_FILES['image']['tmp_name'][$i];
    $filename = $_FILES['image']['name'][$i];
    $output_dir = "images/".$filename;
    if(move_uploaded_file($src, $output_dir )){
        echo "Success! Image uploaded! File: ".$filename;
    }else{
        echo "Error! Image upload failed! File: ".$filename;
    };
    echo "\n<br>";
}

You may also be interested in

About Anto Online

Anto, a seasoned technologist with over two decades of experience, has traversed the tech landscape from Desktop Support Engineer to enterprise application consultant, specializing in AWS serverless technologies. He guides clients in leveraging serverless solutions while passionately exploring cutting-edge cloud concepts beyond his daily work. Anto's dedication to continuous learning, experimentation, and collaboration makes him a true inspiration, igniting others' interest in the transformative power of cloud computing.

View all posts by Anto Online

2 Comments on “How to Upload a File using PHP & Ajax”

  1. now, let’s assume my upload.php file is in a folder.

    I’ve tried setting url: “folder/upload.php” but this doesn’t wor. I also tried with “folder\/upload.php” and “folder\upload.php” and more combinations, but none seem to work.

    any ideas? best regards.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.