Upload Multiple Image Using Ajax in PHP with Preview

Upload Multiple Image Using Ajax in PHP with Preview

In this tutorial, you will learn how to upload multiple images using ajax and jQuery in PHP with preview.

As well as learn how to store images in the PHP project folder.

Sometimes, you need to show the preview before uploading image into a database table and project folder. So This tutorial helps you to show preview of multiple images before uploading to database and project folder using jQuery and ajax in PHP.

Upload Multiple Images using Ajax in PHP with Preview

Follow following the below steps and upload multiple images using ajax and jquery without refreshing page in PHP with preview:

Step 1: Create Image 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>How to upload and display multiple images in php ajax</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>

</head>
<body>
<style type="text/css">
#preview img{
   margin: 5px;
}
</style>
<form method='post' action='' enctype="multipart/form-data">
   <input type="file" id='files' name="files[]" multiple><br>
   <input type="button" id="submit" value='Upload'>
</form>

<!-- Preview -->
<div id='preview'></div>
</body>
<script>
$(document).ready(function(){

$('#submit').click(function(){

   var form_data = new FormData();

   // Read selected files
   var totalfiles = document.getElementById('files').files.length;
   for (var index = 0; index < totalfiles; index++) {
      form_data.append("files[]", document.getElementById('files').files[index]);
 $('#preview').append("<img src='"+URL.createObjectURL(event.target.files[i])+"'>");
   }

   // AJAX request
   $.ajax({
     url: 'ajaxUpload.php', 
     type: 'post',
     data: form_data,
     dataType: 'json',
     contentType: false,
     processData: false,
     success: function (response) {
        alert("Uploaded SuccessFully");
        console.log(response);

     }
   });

});

});
</script>
</html>

This HTML and javascript code shows the image upload form and display image preview before uploading, so using this form you can upload the images on the DB table and project folder with preview.

Step 2: Create Database Connection File

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: Implement PHP Code for Upload File

Create a new file name ajaxUpload.php file and update the below code into your upload.php file.

<?php
require_once "db.php";

// Count total files
$countfiles = count($_FILES['files']['name']);

// Upload directory
$upload_location = "uploads/";

// To store uploaded files path
$files_arr = array();

// Loop all files
for($index = 0;$index < $countfiles;$index++){

   // File name
   $filename = $_FILES['files']['name'][$index];

   // Get extension
   $ext = pathinfo($filename, PATHINFO_EXTENSION);

   // Valid image extension
   $valid_ext = array("png","jpeg","jpg");

   // Check extension
   if(in_array($ext, $valid_ext)){

     // File path
     $path = $upload_location.$filename;

     // Upload file
     if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
        $files_arr[] = $path;

        mysqli_query($conn,"INSERT INTO pictures (title)
		VALUES ('".$path."')");
     }
   }

}

echo json_encode($files_arr);
die;

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

Conclusion

In this tutorial, you have learned how to upload multiple images and display preview using jquery and ajax without a refreshing web page in PHP.

Recommended PHP Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of 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 from a starting stage. As well as demo example.

Leave a Reply

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