Preview Image Before Upload using jQuery in PHP


Show/display image file preview before upload using jQuery ajax in PHP; In this example tutorial, you will learn how to show/display preview image file before upload using jQuery ajax in PHP with MySQL database without refreshing the whole web page.

How to Display Preview Image Before Upload using jQuery in PHP

Follow the following steps on how to display/show preview of an image file before uploading using jQuery ajax in PHP with MySQL database without refreshing the whole web page:

  • Step 1: Create index.php To Display Image File Upload Form
  • Step 2: Create db.php For Database Configuration
  • Step 3: Create upload-image.php to Upload Image into Database using jQuery ajax with php script
  • Step 4: Upload Image File using ajax in PHP

Step 1: Create index.php To Display Image File Upload Form

First of all, create an index.php file and update the below HTML code into your index.php file.

<html lang="en">
<head>
<title>Upload image using php and ajax whithout refreshing page </title>

<!-- Bootstrap Css -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script> 
        $(document).ready(function() { 
            $(".upload-image").click(function(){
            	$(".form-horizontal").ajaxForm({target: '.preview'}).submit();
            });

            function imagePreview(fileInput) {
    if (fileInput.files && fileInput.files[0]) {
        var fileReader = new FileReader();
        fileReader.onload = function (event) {
            $('#preview').html('<img src="'+event.target.result+'" width="300" height="auto"/>');
        };
        fileReader.readAsDataURL(fileInput.files[0]);
    }
}
$("#image").change(function () {
    imagePreview(this);
});
        }); 

</script>
</head>
<body>
	<nav class="navbar navbar-default">
		<div class="container-fluid card">
		<div class="navbar-header">
		<a class="navbar-brand" href="#">PHP - Image Uploading with Form JS Example</a>
		</div>
		</div>
	</nav>
	<div class="container card mt-2 mb-2">
	<form action="upload-image.php" enctype="multipart/form-data" class="form-horizontal" method="post">
		<div id="preview" class="mt-2 mb-2"></div>
		<input type="file" name="image" id="image" class="form-control mt-2 mb-2" style="width:30%" />
		<button class="btn btn-primary upload-image mt-2">Save</button>
	</form>
	</div>
</body>
</html>

The above-given HTML code shows image preview before image upload, so using this form you can show preview before upload the images on the DB table and project folder in php using jQuery ajax.

And this jquery code will show preview of image before upload to database in php using jQuery:

            function imagePreview(fileInput) {
    if (fileInput.files && fileInput.files[0]) {
        var fileReader = new FileReader();
        fileReader.onload = function (event) {
            $('#preview').html('<img src="'+event.target.result+'" width="300" height="auto"/>');
        };
        fileReader.readAsDataURL(fileInput.files[0]);
    }
}
$("#image").change(function () {
    imagePreview(this);
});
        }); 

Step 2: Create db.php For Database Configuration

In this step, create a file name db.php and update the below code into your file.

<?php
	$servername='localhost';
	$username='root';
	$password='';
	$dbname = "my_db";
	$conn=mysqli_connect($servername,$username,$password,"$dbname");
	  if(!$conn){
		  die('Could not Connect MySql Server:' .mysql_error());
		}
?>

This code is used to create a MySQL database connection in your PHP project.

Step 3: Create upload-image.php to Upload Image into Database using jQuery ajax with php script

create a new file name upload-image.php file and update the below code into your upload.php file.

<?php
require_once "db.php";

if(isset($_POST) && !empty($_FILES['image']['name'])){
	

	$name = $_FILES['image']['name'];
	list($txt, $ext) = explode(".", $name);
	$image_name = time().".".$ext;
	$tmp = $_FILES['image']['tmp_name'];


	if(move_uploaded_file($tmp, 'upload/'.$image_name)){
		mysqli_query($conn,"INSERT INTO pictures (title)
		VALUES ('".$image_name."')");
		echo "<img width='200px' src='upload/".$image_name."' class='preview'>";
	}else{
		echo "image uploading failed";
	}


}
?>

This PHP code uploads the image in the DB table and project folder.

Step 4: Start Upload Image File using ajax in PHP App

Let’s start your preview image before uploading using jQuery ajax in PHP with MySQL databse app to upload images into your database.

Conclusion

That’s it; In this example tutorial, you have learned how to show/display preview image file before upload using jQuery ajax in PHP with MySQL database without refresh the whole web page.

Recommended PHP Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?