Image Upload Using Ajax PHP Mysql Tutorial Example

May 13, 2024 | PHP jQuery Ajax


Hello Dev,

Today, I'd like to demonstrate how to create a simple jQuery AJAX image upload with Bootstrap in a PHP project.

Image uploads are a common requirement in web applications. While you can achieve this with just core PHP, utilizing jQuery AJAX offers a more elegant solution without page refreshes. In this post, I'll guide you through creating an image upload feature using jQuery in an easy manner.

For this example, we'll use the jquery.form.js plugin for AJAX image uploads. This plugin simplifies AJAX requests, making it feel like working with PHP code. By following just three steps, you'll have a basic AJAX image upload example ready. Once completed, you'll see a preview similar to the one below.

Read Also: PHP Mysql Crud Integrate Fullcalendar Example

To create a simple jQuery AJAX image upload feature in a PHP project using Bootstrap, follow these steps. This example demonstrates how to upload an image without refreshing the page, providing a smoother user experience.

Step 1: HTML Form Setup

First, create an HTML form for selecting the image file. Use Bootstrap for styling:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Upload Using Ajax PHP Mysql Tutorial Example -- ItErrorSolution.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
    <h2>Image Upload Using Ajax PHP Mysql Tutorial Example -- ItErrorSolution.com</h2>
    <form id="uploadForm" enctype="multipart/form-data">
        <div class="form-group">
            <input type="file" class="form-control" id="image" name="image">
        </div>
        <button type="submit" class="btn btn-primary">Upload</button>
    </form>
    <div id="message"></div>
</div>
<script>
    $(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,
            cache: false,
            processData: false,
            beforeSend: function() {
                $('#message').html('<p>Uploading...</p>');
            },
            success: function(data) {
                $('#message').html('<p>' + data + '</p>');
            },
            error: function() {
                $('#message').html('<p>Something went wrong!</p>');
            }
        });
    });
});
</script>
</body>
</html>
Read Also: jQuery Ajax X-editable bootstrap plugin to update records in PHP Example Step 2: PHP Script for Handling Upload

Create an upload.php file to handle the file upload on the server side:

upload.php
<?php
if(isset($_FILES['image'])) {
    $errors = [];
    $file_name = $_FILES['image']['name'];
    $file_tmp = $_FILES['image']['tmp_name'];
    $file_type = $_FILES['image']['type'];
    $file_ext = strtolower(end(explode('.', $_FILES['image']['name'])));
    $extensions = ["jpeg", "jpg", "png"];

    if(in_array($file_ext, $extensions) === false) {
        $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
    }

    if(empty($errors) == true) {
        move_uploaded_file($file_tmp, "uploads/". $file_name);
        echo "Success";
    } else {
        print_r($errors);
    }
}
?>
Explanation

The HTML form allows users to select an image file.
The jQuery AJAX script sends the selected file to the server without reloading the page.
The PHP script checks the file type and moves the uploaded file to the uploads directory if the file type is valid.

This setup provides a basic image upload feature using jQuery AJAX and PHP. You can further enhance this by adding more sophisticated error handling, file validation, and security measures as needed.

Output: Image Upload Using Ajax PHP Mysql Tutorial Example

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#PHP
#jQuery
#Ajax
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"