I have a form where uses are allowed to upload multiple images, which then are attached to the gallery div for display prior submission of the form. My problem now is that my upload script is not picking up on the handed over attachment variables (neither via POST or GET) since the upload script is expecting the files to be submitted as $_FILES[] variables. How can I pass my attachments to AJAX and send them over to the PHP script in a way that it picks them up?
HTML + JS
<div>
<font>Attachments (.jpg, .png, .bmp):</font>
<input name="file" id="file" type="file" accept="image/*" multiple />
<p class="help-block">Max. filesize 5MB</p>
</div>
<script type="text/javascript" language="javascript">
$(function () {
$("#file").change(function (e) {
e.preventDefault();
var new_img = new FormData(document.getElementById("file"));
new_img.append("label", "new_mod_gallery");
$.ajax({
url: "./templates/upload.php",
type: "POST",
enctype: 'multipart/form-data',
data: new_img,
processData: false,
contentType: false,
cache: false,
success: function(data) {
console.log(data);
$("#lightBoxGallery").load(location.href + " #lightBoxGallery");
},
});
});
});
</script>
upload.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (isset($_POST['label']) && $_POST['label']=='new_mod_gallery') {
// check if any attachments have been selected
if(count($_FILES['file']['name']) > 0) {
// do the upload
} else {
echo "No upload files submitted.";
die();
}
} else { echo "No data received."; }
?>
EDIT: adjusted the JS to include the encodetype as well adjusted the processType and dataType to false as required.
To the poster who flagged this as a duplicate, it is not. My question is how to submit a file upload request via AJAX to PHP and have PHP pick-up the variable as $_FILES[], as opposed to the subject of "How can I upload a file via jquery AJAX" which the linked post is dealing with.