Upload and preview Image without refreshing page using PHP and JavaScript


Images play an important role on our website. We upload images to the website server using the old refresh method, but this is not good in the current modern times. This process should be done without a page refresh and should be very smooth. In this tutorial, we will learn how to upload and preview an image without refreshing the page using PHP and JavaScript. Ever noticed how modern websites let you upload a profile picture and show it to you instantly without reloading the entire page? It feels fast, smooth, and super professional.

We will use the JavaScript (Fetch API) function for instant client-side preview and the PHP PDO prepared statement to insert the image name into the database and move the image file into a folder. You should not use the old PHP method mysqli because it's not secure and causes SQL injection. That’s why we will use a secure PDO prepared statement.
Let’s discuss how it works:
The user selects an image from their computer.
JavaScript intercepts this action, reads the file instantly, and updates the <img> tag on the screen.
In the same way, JavaScript sends the file to a PHP script in the background using an AJAX-style request. The 
PHP script validates the image, validation- file is an image, image size limitation, and saves it into an uploads folder, and updates the database using secure PDO queries.

First of all, we create a database table. Open your phpMyAdmin. 

Step 1: Create MYSQL Database Table 

As you know, the user profile is important for a website. A User selects the image, the image is stored in the database with the user ID and image name, like ID is 1 and image name is myimage.jpg. 
Execute this simple SQL query in your phpMyAdmin to set up a user’s table with a dummy user profile.

We are using the example of a user profile. A user can log in to their account and change the image without refreshing the page.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `fname` varchar(100) DEFAULT NULL,
  `avatar` varchar(255) DEFAULT NULL
);
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `fname`, `avatar`) VALUES
(1, 'Rahul Sharma', NULL);

Step 2. Create a secure PHP connection file

Instead of using MYSQLI or MySQL's old insecure connection methods, we will use the PHP PDO secure connection method. 
It uses a try-catch block so that if the database crashes, your sensitive database passwords won't leak onto the screen.

config.php

<?php  session_start();
define('DBNAME','tute');
define('DBUSER','root');
define('DBPASS','');
define('DBHOST','localhost');
try {
 $dbc = 'mysql:host=' .DBHOST . ';dbname=' . DBNAME.';utf8';
 $dbc= new PDO($dbc,DBUSER,DBPASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
   $dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
  //echo "Your page is connected with the database successfully.";
} catch(PDOException $e) {
  //echo "Issue -> Connection failed: " . $e->getMessage();
}

?> 

Step 3: Create user profile interface 

As you know, we are creating a user profile and changing the image without a page refresh. Now, we will create a profile page. In this page, we will use a user avatar image with a change button. A User clicks the change image button, and the image gets changed without a page refresh. We use PHP PDO to fetch the image name from the database with the user ID and the image from the folder to display on this page when the page reloads. 

index.php

<?php require_once 'config.php'; 
// Demo User Session ID
$_SESSION['userid'] = 1; 
$userid = $_SESSION['userid'];
try {
    // Secure Prepared Statement to Fetch User Data
    $stmt = $dbc->prepare("SELECT avatar FROM users WHERE id = :id");
    $stmt->execute(['id' => $userid]);
    $row = $stmt->fetch();

    // Default image agar database me kuch na mile
    $currentAvatar = (!empty($row['avatar'])) ? 'uploads/' . $row['avatar'] : 'avatar.png';
} catch (PDOException $e) {
    $currentAvatar = 'avatar.png';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure Ajax Image Upload (PDO)</title>
 <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="upload-container">
    <h3>Edit Profile Picture</h3>
    
    <div class="preview-box">
        <img id="imagePreview" src="<?php echo htmlspecialchars($currentAvatar); ?>" alt="Preview">
    </div>

    <label for="imageInput" class="file-label">Upload New Picture</label>
    <input type="file" id="imageInput" accept="image/*">

    <div id="statusMessage"></div>
</div>
<script src="script.js"></script>

</body>
</html>

Explanation of code – 

It’s normal HTML and PHP PDO code. We are fetching an image from the database and displaying it on the page with an Upload New Picture (Change image) button. Also, here we are using the default avatar.png image because of a null value. 

Note - Download the avatar.png image from the internet and save it in the same folder. 

As you know, we have included a JS code link to handle the process without a page refresh. 
Let’s create that JavaScript file. 

4. Write a JavaScript file code that handles the image process without a page refresh – 

This is the main part of this complete process. We use the FileReader() function to display the preview instantly without refreshing the page, so the user can see the image change process. 
No need to wait, just select the image, and you're done! 
We will use the JavaScript fetch() function, which is used to send a request from the browser to the server. In simple words, it executes a PHP file and handles the process between the PHP file and HTML. 

script.js

document.getElementById('imageInput').addEventListener('change', function(e) {
const file = e.target.files[0];
    const preview = document.getElementById('imagePreview');
    const status = document.getElementById('statusMessage');

    if (file) {
        if (!file.type.startsWith('image/')) {
            status.innerHTML = "<span class='error'>Please select a valid image file!</span>";
            return;
        }

        // Instant Preview
        const reader = new FileReader();
        reader.onload = function(event) {
            preview.src = event.target.result; 
        };
        reader.readAsDataURL(file);

        // Fetch API / AJAX Upload
        status.innerHTML = "Securely uploading...";
        
        const formData = new FormData();
        formData.append('profile_pic', file);

        fetch('upload.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                status.innerHTML = `<span class='success'>${data.message}</span>`;
            } else {
                status.innerHTML = `<span class='error'>${data.message}</span>`;
            }
        })
        .catch(err => {
            status.innerHTML = "<span class='error'>Upload failed. Network error!</span>";
        });
    }
});

Explanation of code – 
When a user clicks the "add new image" button, the change event listener triggers, and the JS function executes. The JavaScript Fetch () function is used to send a browser request to the server and receive a response from the server. The requested response is used in JavaScript code to change the image preview. 

Step 5: PHP Image upload file – 

As we discussed above, the fetch () function executes a PHP file, which is used for validation, image size, image formats, and database insertion without page refresh. The fetch () function receives a response in JSON format from this PHP file. We use a PHP PDO prepared statement to insert the data into the database table. 


Note - Create an empty folder named uploads right next to your PHP files before testing, otherwise your files won't find a folder, and you will get an error or an empty image. 

upload.php

<?php header('Content-Type: application/json');
require_once 'config.php';
if(!isset($_SESSION['userid'])){
    echo json_encode(['status'=>'error','message'=>'Unauthorized access.']);
    exit;
}
$userid = $_SESSION['userid'];
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_FILES['profile_pic'])){
    $file = $_FILES['profile_pic'];
$targetDir = "uploads/";
    $allowedTypes = ['image/jpeg','image/png','image/jpg','image/gif','image/webp'];
    $maxSize = 2 * 1024 * 1024;

    if($file['size'] > $maxSize){
        echo json_encode(['status'=>'error','message'=>'File too large!']);
        exit;
    }
    if(!in_array($file['type'],$allowedTypes)){
        echo json_encode(['status'=>'error','message'=>'Invalid image format!']);
        exit;
    }

    $extension = pathinfo($file['name'],PATHINFO_EXTENSION);

    $newFileName = uniqid('avatar_',true).'.'.$extension;

    $targetFilePath = $targetDir.$newFileName;

    if(move_uploaded_file($file['tmp_name'],$targetFilePath)){

        try{

            $oldImg = $dbc->prepare("SELECT avatar FROM users WHERE id=:id");

            $oldImg->execute(['id'=>$userid]);

            $oldImage = $oldImg->fetchColumn();

                if($oldImage && file_exists($targetDir.$oldImage)){
                    unlink($targetDir.$oldImage);
                }

            $sql = "UPDATE users SET avatar=:avatar WHERE id=:id";

            $stmt = $dbc->prepare($sql);

            $updateStatus = $stmt->execute([
                'avatar'=>$newFileName,
                'id'=>$userid
            ]);

            if($updateStatus){

                echo json_encode(['status'=>'success','message'=>'Profile updated!','filename'=>$newFileName]);

            }else{
                throw new Exception();
            }

        }catch(Exception $e){

            if(file_exists($targetFilePath)){
                unlink($targetFilePath);
            }

            echo json_encode(['status'=>'error','message'=>'Database error.']);
        }

    }else{

        echo json_encode(['status'=>'error','message'=>'Upload failed.']);
    }

}else{

    echo json_encode(['status'=>'error','message'=>'Invalid request.']);
}

?>

Step 6. Designing a user profile page with CSS – 

Use CSS to design a user profile page. 

style.css

body{
    margin:0;
    height:100vh;
    display:grid;
    place-items:center;
    font-family:'Segoe UI',sans-serif;
    background:#f4f7f6;
}

.upload-container{
    width:350px;
    padding:30px;
    text-align:center;
    background:#fff;
    border-radius:12px;
    box-shadow:0 8px 24px rgba(0,0,0,.1);
}

h3{
    margin:0 0 20px;
    color:#333;
}

.preview-box{
    width:150px;
    aspect-ratio:1;
    margin:0 auto 20px;
    border:4px solid #00acc1;
    border-radius:50%;
    overflow:hidden;
    background:#e0e0e0;
}

.preview-box img{
    width:100%;
    height:100%;
    object-fit:cover;
}

.file-label{
    display:inline-block;
    padding:10px 20px;
    border-radius:25px;
    background:#00acc1;
    color:#fff;
    font-weight:600;
    cursor:pointer;
    transition:.3s;
}

.file-label:hover{
    background:#00838f;
}

#imageInput{
    display:none;
}

#statusMessage{
    margin-top:15px;
    font:700 14px sans-serif;
}

.success{color:#2e7d32}
.error{color:#c62828}

Now, test your code. Click the " add new image"  button. If the button does not work, check the JavaScript error in the console, and also check the upload.php file. 
In this way, you can upload an image without refreshing the page using PHP, MySQL, and JavaScript. 


Please Share

Previous Posts:-

Featured Items:-


Ecommerce system in PHP website | Digital Ecommerce Shop web app

$66



Paypal Payment form in PHP website with MYSQL database | International Payments

$12



Payment form by PayUmoney gateway with GST invoice,email | PHP software

$38





0 Comment