Image upload and preview using jQuery AJAX in PHP

  • Tech Area
  • May 13, 2024



In this tutorial, We will learn how to upload image and preview using JQuery AJAX in PHP.

Files used in this tutorial:

1- index.php (AJAX script)

2- upload.php (upload image)

Below are the step by step process of how to upload image and preview using Jquery AJAX.

Step 1: Create index.php

In this step, create a new file index.php. This is the main file used to implement AJAX to upload and preview image using AJAX in PHP.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload and Preview</title>
</head>
<body>
    <input type="file" id="imageUpload" accept="image/*">
    <div id="imagePreview"></div>
</body>
</html>

Now use jquery AJAX script.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function(){
        $('#imageUpload').change(function(){
            var formData = new FormData();
            var file = $(this)[0].files[0];
            formData.append('file', file);

            $.ajax({
                url: 'upload.php',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response){
                    $('#imagePreview').html('<img src="' + response +'" height=100>');
                }
            });
        });
    });
</script>

Step 2: Create new file for upload image

In this step, create a new file upload.php. This file used to upload image into the directory.

upload.php

<?php
if(isset($_FILES['file']))
{
	$file = $_FILES['file'];
	$file_name = $file['name'];
	$file_tmp = $file['tmp_name'];

	$file_ext = explode('.', $file_name);
	$file_ext = strtolower(end($file_ext));

	$file_name_new = uniqid('',true).'.'.$file_ext;
	$file_destination = 'uploads/'.$file_name_new;

	if(move_uploaded_file($file_tmp, $file_destination))
	{
		echo $file_destination;
	}
}
?>

Download Source Code


Subscribe us via Email

Join 10,000+ subscriber

Subscribe on YouTube