I want to make a multiple image upload function where the user can upload images and can remove specific images from the uploaded ones. So my plan was, when the user selects the images, a demo preview of the images will appear, with a remove button.
When the user selects the images, on the input
change, a loop gets the files from the input and pushes them into an array. So if the user decides to upload more images, the loop will add the new ones to the array. And if the user clicks the remove button, it removes the selected item from the array.
After the user selected the images, on button click an AJAX function posts the values to a PHP file which processes it and uploads it into a datebase. So basically everything would work fine if I was POST the default input.files
with the AJAX but I want to POST the array
with the files in it but I get an error: undefined index
.
test.html:
let array = [];
$('body').on('click', '#upload', function(e){
e.preventDefault();
var el = document.getElementById("file").files;
for (let i = 0; i < el.length; i++) {
array.push(el[i]);
} console.log(array);
$.ajax({
url: 't.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
$('#preview').html(data);
},
data: array,
cache: false,
contentType: false,
processData: false
});
return false;
});
<html lang="en">
<head>
<title>How to upload and display multiple images in php ajax</title>
<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 enctype="multipart/form-data" method="post">
<input name="file[]" id="file" type="file" multiple />
<input type="button" id="upload" value="Upload File" />
</form>
<div id="preview"></div>
</body>
</html>
t.php:
<?php
error_reporting(E_ALL | E_STRICT);
var_dump($_POST['data']);
for($i=0; $i<count($_POST['data']['name']); $i++){
$target_path = $_SERVER['DOCUMENT_ROOT'].'/assets/images/uploads/';
$ext = explode('.', basename( $_POST['data']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_POST['data']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
?>