How to Upload Files Using JavaScript Ajax & PHP

Upload Files Using JavaScript Ajax & PHP

In web development, you might often need to implement file uploads to allow users to upload files to your server. JavaScript combined with AJAX provides a powerful way to perform file uploads asynchronously without requiring the page to refresh. in this tutorial you will learn how to implement file uploads using JavaScript, AJAX, and PHP.

There are few methods to Implement AJAX in JavaScript like – using Fetch API, Axios Library, and using XMLHttpRequest. Here we will explore all these three ways to upload files.

Setup the Project Folder:

To upload files we will use PHP in the backend, so I hope you have PHP development environment. Now, go to your localhost directory (htdocs folder of xampp) and create a new folder called php-ajax-upload. Here is the folder structure:

php-ajax-upload/
β”œβ”€β”€ uploads/
β”œβ”€β”€ index.html
└── upload.php

“upload.php” For Uploading Files to the Server

The upload.php files is responsible for uploading files to the server. It will move the files into the uploads folder. Here is the code of this file:

<?php
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $targetDir = 'uploads/'; // Specify the target directory
    $targetFile = $targetDir . basename($_FILES["file"]["name"]); // Get the file name

    // Check if file already exists
    if (file_exists($targetFile)) {
        echo 'Sorry, the file already exists.';
    } else {
        // Move the uploaded file to the specified directory
        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
            echo 'File uploaded successfully!';
        } else {
            echo 'Error uploading file!';
        }
    }
}

If you want to know how to use PHP to upload files then checkout this – How To Upload Files using PHP.

Using AJAX to Submit Files to the upload.php

Now we will see how we can use AJAX to submit files to the server for uploading. Here we will see three approaches to make file uploading ajax request – Fetch API, Axios, and XMLHttpRequest.

Here is the index.html that includes an input element for file selection, a button to trigger the upload process, and a boiler-plate JS code for uploading files using AJax. The JS ajax code has been omitted as we will add in further steps.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Ajax File Upload</title>
    </head>
    <body>
        <label for="fileInput">Choose a file:</label>
        <input type="file" name="file" id="fileInput" />
        <button id="uploadBtn">Upload File</button>
        <script>
            const uploadBtn = document.getElementById("uploadBtn");
            const url = "http://localhost/php-ajax-upload/upload.php";
            uploadBtn.onclick = function (e) {
                e.preventDefault();
                const fileInput = document.getElementById("fileInput");
                const file = fileInput.files[0];
                const formData = new FormData();
                formData.append("file", file);

                // Ajax File Upload Code will Goes Here

            };
        </script>
    </body>
</html>

Fetch API Ajax Code for Uploading Files:

Fetch API, a modern approach that offer a promise-based interface for making network requests. Using Fetch API for file uploads involves creating a FormData object, appending the file to it, and passing it as the body of a POST request. Fetch API supports streaming requests and responses, making it an efficient choice for handling file uploads. Add this code into the index.html file:

fetch(url, {
    method: "POST",
    body: formData,
})
    .then((res) => res.text())
    .then((data) => {
        alert(data);
    })
    .catch((error) => {
        alert("Error uploading file.");
        console.error("Error:", error);
    });

Using Axios to Upload Files:

Axios is a popular HTTP client library that simplifies making HTTP requests in JavaScript. For file uploads, Axios provides a straightforward method akin to Fetch API, requiring the creation of a FormData object and passing it as the request body.

To use axios, first you need to install it or add CDN into the index.html:

<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>

Now you can use axios:

axios
    .post(url, formData)
    .then((res) => {
        alert(res.data);
    })
    .catch((err) => {
        alert(err.message);
        console.log(err);
    });
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Ajax File Upload</title>
    </head>
    <body>
        <label for="fileInput">Choose a file:</label>
        <input type="file" name="file" id="fileInput" />
        <button id="uploadBtn">Upload File</button>

        <script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
        <script>
            const uploadBtn = document.getElementById("uploadBtn");
            const url = "http://localhost/php-ajax-upload/upload.php";
            uploadBtn.onclick = function (e) {
                e.preventDefault();
                const fileInput = document.getElementById("fileInput");
                const file = fileInput.files[0];
                const formData = new FormData();
                formData.append("file", file);

                // Axios
                axios
                    .post(url, formData)
                    .then((res) => {
                        alert(res.data);
                    })
                    .catch((err) => {
                        alert(err.message);
                        console.log(err);
                    });
            };
        </script>
    </body>
</html>

Using XMLHttpRequest for Uploading Files via Ajax:

XMLHttpRequest has long been the workhorse of AJAX requests in JavaScript. It provides a robust, albeit verbose, means of communication with a server. When it comes to file uploads, XMLHttpRequest requires setting up an instance, defining event listeners for progress tracking, and manually handling the request. Here is the XMLHttpRequest code for uploading files via ajax:

const xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onload = function () {
    if (xhr.status === 200) {
        const responseData = xhr.responseText;
        alert(responseData);
    } else {
        alert("Error uploading file.");
        console.error(xhr.status + " - " + xhr.statusText);
    }
};
xhr.send(formData);

Conclusion:

This is a very simple tutorial that gives you an idea to uploading files via Ajax. Each of the discussed methods – XMLHttpRequest, Fetch API, and Axios offers a distinct approach to handling file uploads in JavaScript. While XMLHttpRequest remains a stalwart option, its verbosity and lack of modern features may deter developers seeking cleaner code. Fetch API and Axios, on the other hand, provide more concise syntax and additional features, making them well-suited for contemporary web development. Ultimately, the choice between these methods depends on project requirements, compatibility considerations, and developer preferences.

Leave a Reply

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

We use cookies to ensure that we give you the best experience on our website. Privacy Policy