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 quite 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. In this case, you do not want the form to submit. 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. For this post, we will make the AJAX call on the onchange event of the #imageButton element.

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 its 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 to not convert the object data into url-encoded string.

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

This option can also be set to 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 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 the 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

In 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>";
}

Conclusion

Formdata() and AJAX together can be very powerful. These can also be used for data transfer of 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>";
}



About the Authors

Each member of Anto's editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic!

Support the Cause

Support Anto Online and buy us a coffee. Anything is possible with coffee and code.

Buy me a coffee



Leave a Reply

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