Skip to content
Rishan Solutions
Rishan Solutions
  • PowerApps
  • SharePoint online
    • Uncategorized
    • Uncategorized
  • PowerAutomate
Rishan Solutions
Latest Posts
  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025 June 24, 2025
  • Recursive Queries in T-SQL May 7, 2025
  • Generating Test Data with CROSS JOIN May 7, 2025
  • Working with Hierarchical Data May 7, 2025
  • Using TRY_CAST vs CAST May 7, 2025
  • Dynamic SQL Execution with sp_executesql May 7, 2025

Implementing file uploads using AJAX and jQuery

Posted on March 24, 2025March 24, 2025 by Zubair Shaik

Loading

Implementing File Uploads Using AJAX and jQuery – A Complete Guide

Introduction

File uploads are a common requirement in modern web applications, allowing users to upload images, documents, and other media. Traditionally, file uploads required a full-page refresh, but with AJAX and jQuery, we can perform asynchronous file uploads, providing a smoother user experience.

Why Use AJAX for File Uploads?

  • No Page Refresh – The user can continue using the application without interruptions.
  • Better User Experience – Provides progress updates and instant feedback.
  • Efficient – Uploading happens in the background without reloading the page.
  • Asynchronous Processing – Helps handle large file uploads without blocking the UI.

What Will We Cover?

This guide covers everything about AJAX-based file uploads using jQuery, including:

  1. Understanding AJAX and File Uploads
  2. Setting Up the HTML Form
  3. Using jQuery and AJAX to Handle File Uploads
  4. Handling File Uploads on the Server (PHP Example)
  5. Displaying Upload Progress
  6. Validating Files Before Upload
  7. Handling Multiple File Uploads
  8. Displaying Uploaded Files
  9. Best Practices for Secure File Uploads
  10. Troubleshooting Common Issues

1. Understanding AJAX and File Uploads

AJAX stands for Asynchronous JavaScript and XML, allowing the browser to communicate with the server without refreshing the page. When it comes to file uploads, AJAX handles the request asynchronously, sending the file data in the background.

Challenges with File Uploads in AJAX

  • Files need to be sent as FormData instead of plain JSON.
  • Browser security restrictions on large file uploads.
  • Different server-side processing is required for handling file streams.

2. Setting Up the HTML Form

To upload a file, we need an HTML form with an input field for selecting files.

Basic HTML File Upload Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX File Upload</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

    <h2>Upload File using AJAX</h2>
    
    <form id="uploadForm">
        <input type="file" id="fileInput" name="file">
        <button type="submit">Upload</button>
    </form>

    <p id="uploadStatus"></p>

    <script src="upload.js"></script>

</body>
</html>

Key Elements

  • <input type="file"> – Allows the user to select a file.
  • <button type="submit"> – Triggers the upload.
  • <p id="uploadStatus"> – Displays the upload status.

3. Using jQuery and AJAX to Handle File Uploads

Now, let’s use jQuery to handle the file upload asynchronously.

AJAX File Upload using jQuery

$(document).ready(function() {
    $("#uploadForm").on("submit", function(e) {
        e.preventDefault(); // Prevent default form submission

        var file = $("#fileInput")[0].files[0]; // Get the selected file
        if (!file) {
            alert("Please select a file to upload.");
            return;
        }

        var formData = new FormData();
        formData.append("file", file);

        $.ajax({
            url: "upload.php", // Server-side script to handle upload
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                $("#uploadStatus").html("<p>File uploaded successfully: " + response + "</p>");
            },
            error: function(xhr, status, error) {
                $("#uploadStatus").html("<p>Error uploading file: " + error + "</p>");
            }
        });
    });
});

How It Works

  1. Prevents the default form submission.
  2. Gets the selected file using $("#fileInput")[0].files[0].
  3. Creates a FormData object and appends the file.
  4. Sends the file using $.ajax():
    • contentType: false prevents jQuery from adding a default content type.
    • processData: false ensures data is sent as FormData.

4. Handling File Uploads on the Server (PHP Example)

The server-side script (e.g., upload.php) will handle the uploaded file.

PHP Server-Side Script

<?php
if ($_FILES['file']['name']) {
    $uploadDir = "uploads/";
    $fileName = basename($_FILES["file"]["name"]);
    $targetFile = $uploadDir . $fileName;

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
        echo $fileName;
    } else {
        echo "Error uploading file.";
    }
} else {
    echo "No file received.";
}
?>

How It Works

  • $_FILES['file'] retrieves the uploaded file.
  • move_uploaded_file() moves the file to the uploads/ directory.
  • Returns the filename if successful or an error message if failed.

5. Displaying Upload Progress

We can show a progress bar while uploading.

Modify AJAX Request for Progress Tracking

$.ajax({
    url: "upload.php",
    type: "POST",
    data: formData,
    contentType: false,
    processData: false,
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(e) {
            if (e.lengthComputable) {
                var percentComplete = (e.loaded / e.total) * 100;
                $("#uploadStatus").html("<p>Uploading: " + percentComplete.toFixed(2) + "%</p>");
            }
        }, false);
        return xhr;
    },
    success: function(response) {
        $("#uploadStatus").html("<p>Upload Complete: " + response + "</p>");
    }
});

6. Validating Files Before Upload

Client-Side Validation

var file = $("#fileInput")[0].files[0];

if (file.size > 5 * 1024 * 1024) { // 5MB limit
    alert("File is too large. Max size is 5MB.");
    return;
}

var allowedTypes = ["image/jpeg", "image/png", "image/gif"];
if (!allowedTypes.includes(file.type)) {
    alert("Only JPG, PNG, and GIF files are allowed.");
    return;
}

7. Handling Multiple File Uploads

Modify HTML

<input type="file" id="fileInput" name="files[]" multiple>

Modify JavaScript

var formData = new FormData();
var files = $("#fileInput")[0].files;

for (var i = 0; i < files.length; i++) {
    formData.append("files[]", files[i]);
}

Modify PHP to Handle Multiple Files

foreach ($_FILES['files']['name'] as $key => $name) {
    move_uploaded_file($_FILES['files']['tmp_name'][$key], "uploads/" . $name);
}

8. Displaying Uploaded Files

After upload, list the uploaded files dynamically.

$("#uploadStatus").append("<img src='uploads/" + response + "' width='100'>");

9. Best Practices for Secure File Uploads

  • Validate file type before upload.
  • Limit file size to prevent abuse.
  • Rename files to avoid conflicts.
  • Use mime_content_type() for server-side validation.

10. Troubleshooting Common Issues

IssueSolution
No file receivedEnsure enctype="multipart/form-data" is set.
Large files failIncrease upload_max_filesize in PHP.
Wrong file type allowedUse finfo_open(MIME_TYPE).

In this guide, we covered AJAX file uploads with jQuery, progress tracking, error handling, multiple uploads, and security best practices.

Would you like a backend example in Node.js or Python?

Posted Under jQuery`AJAX file upload AJAX document upload AJAX drag and drop file upload AJAX file upload and processing AJAX file upload and validation AJAX file upload API AJAX file upload async AJAX file upload authentication AJAX file upload AWS S3 AJAX file upload backend processing AJAX file upload best practices AJAX file upload CORS AJAX file upload cross-browser AJAX file upload debugging AJAX file upload Django AJAX file upload error handling AJAX file upload example AJAX file upload Firebase AJAX file upload Flask AJAX file upload HTML5 AJAX file upload in Angular AJAX file upload in jQuery UI AJAX file upload Java AJAX file upload JavaScript AJAX file upload JSON response AJAX file upload Laravel AJAX file upload large files AJAX file upload Node.js AJAX file upload PHP AJAX file upload progress bar AJAX file upload REST API AJAX file upload restrictions AJAX file upload security AJAX file upload security best practices AJAX file upload session management AJAX file upload Spring Boot AJAX file upload status updates` AJAX file upload success message AJAX file upload to cloud storage AJAX file upload to server AJAX file upload tutorial AJAX file upload UI enhancement AJAX file upload using XHR AJAX file upload validation AJAX file upload with FormData AJAX file upload with metadata AJAX file upload with percentage progress AJAX file upload with PHP MySQL AJAX file upload with preview AJAX file upload with progress AJAX file upload with progress indicator AJAX file upload with React.js AJAX file upload with Vue.js AJAX file upload without refreshing AJAX image file upload AJAX image upload AJAX multiple file upload AJAX multiple file upload PHP AJAX secure file upload asynchronous file upload jQuery AJAX file upload jQuery AJAX file upload example jQuery file upload jQuery FormData file upload

Post navigation

Material-UI Components
Introduction to Hooks

Leave a Reply Cancel reply

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

Recent Posts

  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025
  • Recursive Queries in T-SQL
  • Generating Test Data with CROSS JOIN
  • Working with Hierarchical Data
  • Using TRY_CAST vs CAST

Recent Comments

  1. Michael Francis on Search , Filter and Lookup in power apps
  2. A WordPress Commenter on Hello world!

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • March 2024
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023
  • April 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • January 2022

Categories

  • Active Directory
  • AI
  • AngularJS
  • Blockchain
  • Button
  • Buttons
  • Choice Column
  • Cloud
  • Cloud Computing
  • Data Science
  • Distribution List
  • DotNet
  • Dynamics365
  • Excel Desktop
  • Extended Reality (XR) – AR, VR, MR
  • Gallery
  • Icons
  • IoT
  • Java
  • Java Script
  • jQuery
  • Microsoft Teams
  • ML
  • MS Excel
  • MS Office 365
  • MS Word
  • Office 365
  • Outlook
  • PDF File
  • PNP PowerShell
  • Power BI
  • Power Pages
  • Power Platform
  • Power Virtual Agent
  • PowerApps
  • PowerAutomate
  • PowerPoint Desktop
  • PVA
  • Python
  • Quantum Computing
  • Radio button
  • ReactJS
  • Security Groups
  • SharePoint Document library
  • SharePoint online
  • SharePoint onpremise
  • SQL
  • SQL Server
  • Template
  • Uncategorized
  • Variable
  • Visio
  • Visual Studio code
  • Windows
© Rishan Solutions 2025 | Designed by PixaHive.com.
  • Rishan Solutions