Learn how to upload multiple images using jQuery ajax in PHP
Before writing code let's see my project structure then create the file as it is this will help you to build multiple images upload using jQuery ajax in PHP without refreshing the page.
Project structure
Upload-Multiple/
┣ images/
┣ index.php
┗ upload.php
Images: is our directory name where we will upload multiple images on server.
Create an index.php file and put the following code
<!DOCTYPE html>
<html>
<head>
<title>How To Upload Multiple Images Using JQuery Ajax In PHP</title>
<style>
form{
width: 800px;
background: #cc0033;
padding: 20px;
color: #fff;
margin: 100px auto;
}
</style>
</head>
<body>
<div id="showimages"></div>
<form id="upload-form" method="post" action="" enctype="multipart/form-data">
<label>Choose files :</label>
<input type="file" name="images[]" multiple="multiple">
<button type="submit">Upload Now</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#upload-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "post",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
$("#showimages").html(data);
}
});
});
});
</script>
</body>
</html>
Now Create upload.php file and put the following code
<?php
//count total files
$total = count($_FILES['images']['name']);
// Loop through each file
$output = '';
for ($i = 0; $i < $total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['images']['tmp_name'][$i];
//Make sure we have a file path
if ($tmpFilePath != "") {
//Setup our new file path
$newFilePath = "./images/" . $_FILES['images']['name'][$i];
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$output .= '<img src="' . $newFilePath . '" width="100px" height="100px" />';
}
}
}
echo $output;
?>
code is 100% tested will work for you to build multiple file upload using jquery in PHP
Output: