Preview Image Before Upload using jQuery 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?

Here are steps:

  • 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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *