How to Make Image Upload Code Using AJAX

AJAX image upload using PHP and jQuery

Uploading images without refreshing the page is one of the most common features in modern web applications. If you want to build a smooth user experience for profile pictures, gallery uploads, product images, or blog thumbnails, then learning how to make image upload code using AJAX is essential. AJAX allows the file upload process to happen asynchronously — meaning the user does not have to reload the page. In this article, we will walk through the complete process, including HTML form setup, JavaScript AJAX request, PHP backend processing, error handling, and security best practices.

This guide is ideal for beginners and intermediate developers who want to create a real-world image upload feature using AJAX and PHP in 2025.


What Is AJAX and Why Use It for Image Uploads?

AJAX stands for Asynchronous JavaScript and XML, and it allows web pages to update content without refreshing.

Benefits of AJAX Image Upload

  • Faster and smoother user experience
  • No full page reload
  • Instant preview before uploading
  • Reduced server load
  • Better UI for mobile devices

Popular platforms like Facebook, Instagram, and WordPress use AJAX-based uploads because of their speed and efficiency.

For more details, check the official MDN AJAX guide:
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX


Folder Structure for AJAX Image Upload

Before writing code, create this structure:

/ajax-upload/
│── index.html
│── upload.php
│── uploads/

Important Notes

  • The uploads folder must have write permissions
  • On Linux hosting, set folder chmod to: 755 or 775

Step 1 — Create the HTML Form

Create index.html with a file input and preview section.

HTML Form Code

<!DOCTYPE html>
<html>
<head>
    <title>AJAX Image Upload</title>
</head>
<body>

<h2>Upload Image Using AJAX</h2>

<form id="uploadForm" enctype="multipart/form-data">
    <input type="file" name="image" id="image" required>
    <button type="submit">Upload</button>
</form>

<div id="preview"></div>
<div id="response"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="upload.js"></script>

</body>
</html>

Features Included

  • No page refresh
  • jQuery included
  • Preview and response areas ready

Step 2 — AJAX Request Using jQuery

Create upload.js to send image data using AJAX and FormData.

AJAX Code

$(document).ready(function() {
    $("#uploadForm").on('submit', function(e) {
        e.preventDefault();

        var formData = new FormData(this);

        $.ajax({
            url: "upload.php",
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                $("#response").html(response);
            }
        });
    });
});

Why FormData?

  • Supports file objects
  • Sends binary data
  • Works with AJAX seamlessly

Learn more from MDN:
https://developer.mozilla.org/en-US/docs/Web/API/FormData


Step 3 — PHP Backend to Handle Upload

Create upload.php to move the file into the uploads folder.

PHP Upload Handling Code

<?php

if(isset($_FILES['image'])){

    $fileName = $_FILES['image']['name'];
    $fileTmp = $_FILES['image']['tmp_name'];

    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($fileName);

    $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
    $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    if(!in_array($fileType, $allowedTypes)){
        echo "Only JPG, PNG, GIF files are allowed";
        exit;
    }

    if(move_uploaded_file($fileTmp, $targetFile)){
        echo "Image uploaded successfully";
        echo "<br><img src='$targetFile' width='200'>";
    } else {
        echo "Upload failed. Try again.";
    }

} else {
    echo "No file selected";
}
?>

Adding Live Image Preview (Optional Upgrade)

Add this script inside index.html:

$('#image').change(function() {
    let reader = new FileReader();
    reader.onload = function(e) {
        $('#preview').html('<img src="'+e.target.result+'" width="200">');
    };
    reader.readAsDataURL(this.files[0]);
});

Benefits

  • User sees image before upload
  • Improves UI/UX

Security Best Practices for Image Upload

Do This:

  • Validate file extensions
  • Restrict file size
  • Rename uploaded files
  • Disable direct file access
  • Store outside public folders if needed

Never Do:

  • Allow executable files
  • Store original filename
  • Skip validation

More security reference (OWASP):
https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload


Internal Links (Examples for Your Blog)

You can link to your related posts like:

  • How to Create Database Connection and Encrypt Password in PHP (2025 Guide)
  • PHP Form Validation Tutorial for Beginners
  • Best Hosting Providers for PHP Developers in 2025

Internal linking improves SEO and user engagement.


Conclusion

Using AJAX for image upload is one of the most efficient ways to build modern, user-friendly applications in 2025. With the combination of HTML, jQuery, FormData, and PHP, you can upload images without page reload, display instant previews, and create a seamless user experience. Always remember to apply security validation, restrict file types, and handle server permissions properly. By implementing the steps covered in this guide, you are now ready to integrate AJAX image upload into any real-world web project confidently.

Leave a Comment

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