How to Implement a Seamless jQuery File Upload with AJAX

28 Jul

jQuery file upload is a simple and efficient way to enhance user experience on your website. In this guide, I’ll walk you through how to upload a file using AJAX and jQuery, providing a modern and responsive approach to handling file uploads.

Step 1: Setting Up jQuery

First, ensure you have the latest jQuery library. You can download it from the official jQuery website or include it directly from Google’s CDN. While using a CDN is convenient, for production environments, it’s recommended to host the jQuery file locally on your server.

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

Step 2: HTML Structure

Create a simple HTML structure with an input field for file selection and a button to trigger the upload process.

<body>
  <div>
    <label for="my_image">Upload Image</label>
    <input type="file" name="my_image" id="my_image" onChange="onChangeHandler(event)" />
  </div>
  <div>
    <input type="button" value="Upload" name="upload_file" onClick="saveFile()" />
  </div>
  <div id="results"></div>
</body>

In this setup, the onChangeHandler function captures the selected file, and the saveFile function handles the file upload.

Step 3: JavaScript Functions for Handling File Upload

Define the necessary JavaScript functions to handle the file selection and upload using AJAX.

<script>
  const data = new FormData();

  function onChangeHandler(event) {
    data.append('file', event.target.files[0]);
  }

  function saveFile() {
    $.ajax({
      type: "POST",
      url: 'uploadfile.php',
      data: data,
      contentType: false,
      processData: false,
      success: function(response) {
        $("#results").html(response);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        $("#results").html(`<p>Error: ${textStatus}</p>`);
      }
    });
  }
</script>

Here, FormData is used to construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the $.ajax method. The contentType and processData options must be set to false to correctly send the file data.

Step 4: Server-Side File Handling with PHP

On the server side, you’ll need a PHP script to handle the incoming file upload request. This script will save the uploaded file and return a response.

<?php
if ($_FILES) {
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 2000000)
    && in_array($extension, $allowedExts)) {
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        } else {
            $filename = "upload/" . $_FILES["file"]["name"];
            move_uploaded_file($_FILES["file"]["tmp_name"], $filename);
            echo json_encode(array(
                "status" => "success",
                "message" => "File uploaded successfully!",
                "path" => $filename
            ));
        }
    } else {
        echo json_encode(array(
            "status" => "error",
            "message" => "Invalid file"
        ));
    }
}
?>

In this script, we validate the file type and size before saving it to the server. If the file meets the criteria, it is saved in the “upload” directory, and a success message is returned. Otherwise, an error message is displayed.

Step 5: Testing the File Upload Feature

Create the HTML and PHP files as described and place them in your local server environment (e.g., XAMPP, WAMP). Open the HTML file in your browser and test the file upload functionality. Ensure your “upload” directory has appropriate permissions for file writing.