In this tutorial we will learn how to upload image without refreshing page using jquery, ajax and php. If there is requirement like upload image without refreshing page and show the preview. Noways, this kind of functionality is implemented in facebook, twitter profile pic upload.

Create users table in mysql: 

Below is the structure of users table with basic fields. 

CREATE TABLE `users` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `email` VARCHAR(80) NULL,
  `mobile` VARCHAR(50) NULL,
  `profile_pic` VARCHAR(50) NULL,
  `bio` TEXT 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>Ajax Image Upload without Refreshing Page using Jquery 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>
            .avatar,.avatar img{
                height:200px;
                width:200px;
                border-radius:100%;
                background-color: #ccc;
            }
        </style>
    </head>
    <body>
        <div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">  
            <div>
                <h2 style="margin-bottom:50px;">Live Demo: Ajax Image Upload without Refreshing Page using Jquery and Php.</h2>
                <div>
                    <form method="post" enctype="multipart/form-data" action="save.php" id="form_image" name="form_image" onsubmit="return false">
                        <div class="avatar" id="avatar">
                            <img src="https://www.photogur.com/assets/images/default_profile.png" id="user_avatar" class="img-responsive"/>
                        </div>
                        <input type="file" name="userfile" id="userfile" style="display:none;" accept="image/x-png,image/gif,image/jpeg">
                        <a href="javascript:void(0);" id="call_file_upload" class="btn btn-success" style="margin-top: 20px;">Change Avatar</a>
                    </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") {
                                        $("#user_avatar").attr('src', data.img);
                                        $('#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