In tutorial we will learn how to upload and preview multiple images using jquery, ajax and php. Image upload is most commonly used functionality 

in the web application development. Sometimes we have requirement like upload multiple images without refreshing page and preview the uploaded images.
 The example code helps you to upload multiple images and preview them on webpage. Here we will store the images in database and after that we will show them and webpage. 

Create post_images table in mysql: 
Below is the structure of post_images table with basic fields. 

CREATE TABLE `post_images` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `img_path` VARCHAR(100) NULL,
  `post_id` INT NULL,
  `created_at` DATETIME NULL,
  `updated_at` DATETIME NULL,
  PRIMARY KEY (`id`));

  

Create Connection(config.php) 

Connect to the database. In config.php add your database name, database username, database password and database name. 

<?php
//Database details
$db_host = 'localhost';
$db_username = 'username';
$db_password = 'password';
$db_name = 'database_name';

//Create connection and select DB
$conn = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

index.php 

<!--
Used basic html and bootstrap skeleton from the below link for style purpose which contains bootstrap.css,bootstrap.js,jquery.js
https://www.w3schools.com/bootstrap/bootstrap_get_started.asp
Used bootstrap form elements from below link.
https://www.w3schools.com/bootstrap/bootstrap_forms.asp-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Upload and Preview Multiple Images using jQuery, Ajax and PHP.</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">      
        <style>
            .img-box{
                max-height: 300px;
                margin-bottom: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">  
            <div>
                <h2 style="margin-bottom:50px;">Live Demo: Upload and Preview Multiple Images using jQuery, Ajax and PHP.</h2>
                <div>
                    <form method="post" enctype="multipart/form-data" action="save.php" id="form_image" name="form_image" onsubmit="return false">
                        <div style="margin-bottom:20px;">
                            <input type="file" name="userfile[]" id="userfile" style="display:none;" accept="image/x-png,image/gif,image/jpeg" multiple>
                            <a href="javascript:void(0);" id="call_file_upload" class="btn btn-success" style="margin-top: 20px;">Select Multiple Images</a>
                        </div>
                        <div class="uploaded-img-wrap">
                            <div class="img-box" style="display:none;"></div>
                        </div>
                        <div class="clearfix"></div>                      
                    </form>
                </div>
            </div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script>
                        $(document).on("click", "#call_file_upload", function () {
                            $("#userfile").trigger('click');
                        });
                        $(document).on("change", "#userfile", function () {
                            formData = new FormData(document.forms.namedItem("form_image"));
                            $.ajax({
                                url: 'save.php',
                                type: 'POST',
                                data: formData,
                                cache: false,
                                contentType: false,
                                processData: false,
                                dataType: 'json',
                                success: function (data) {
                                    if (data.result == "success") {
                                        $(data.imgs).insertBefore('.img-box:first');
                                        $('#form_image')[0].reset();
                                    } else {
                                        console.log(data.msg);
                                    }
                                }
                            });
                        });
        </script>
    </body>
</html>


save.php

<?php

require_once 'config.php';
$session_id = 1;
if (isset($_FILES['userfile']['name']) && $_FILES['userfile']['name'] != "") {
    $tmp = $_FILES['userfile']['tmp_name'];
    $actual_image_name = "uploads/" . $_FILES['userfile']['name'];
    if (move_uploaded_file($tmp, $actual_image_name)) {
        mysqli_query($db, "UPDATE users SET profile_pic='$actual_image_name' WHERE uid='$session_id'");
        echo json_encode(array("result" => "success", "img" => $actual_image_name, "msg" => "Profile avatar changed successfully."));
    } else {
        echo json_encode(array("result" => "fail", "img" => $actual_image_name, "msg" => "Server problem. Try after sometime."));
    }
} else {
    echo json_encode(array("result" => "fail", "img" => $actual_image_name, "msg" => "Please select file to upload."));
}
?>
Written by
Check out this Author's contributed articles.
If you like Tutorialsmint and would like to contribute, you can also write an article using Write an Article. See your article appearing on the Tutorialsmint main page and help other programmers to enhance their knowledge.

Comments(0)

RECENT TUTORIALS
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Edit Post
Add Reply