in this article, we will learn how to image upload with preview in PHP Jquery ajax.



Example

Before writing a code let me show you my project structure


php-tutorial/
images/
┣ index.php
┗ upload.php

image is our destination folder or directory where we will upload an image on the server


index.php

<html>
    <head>
        <title>PHP AJAX Image Upload</title>

        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    </head>
    <body>
        <div class="container">
            <div class="col-md-6 offset-md-3">
                <div class="card">
                    <div class="card-title p-1 bg-primary">
                        <h6>PHP AJAX Image Upload</h6>
                    </div>
                    <div class="card-body">
                        <form id="uploadForm" action="upload.php" method="post">
                            <div class="col-md-12 bg-light mb-2 text-center">
                                <div id="preview">No Image</div>
                            </div>
                            <div class="form-group">
                                <input name="userImage" type="file" class="form-controller" />
                            </div>
                            <input type="submit" value="Submit" class="btn btn-primary" />
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(document).ready(function(e) {
        $("#uploadForm").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: "upload.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,
                success: function(data)
                {
                    $("#preview").html(data);
                },
                error: function()
                {
                }
            });
        }));
    });
</script>
</html>



upload.php

<?php
if (is_array($_FILES)) {
    if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
        $sourcePath = $_FILES['userImage']['tmp_name'];
        $destination_path = "images/" . $_FILES['userImage']['name'];
        if (move_uploaded_file($sourcePath, $destination_path)) {
            ?>
            <img class="img-fluid" width="100%" height="100" src="<?php echo $destination_path; ?>" />
            <?php
        }
    }
}
?>


Output: