In my form.php
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file_upload[]" id="file_upload" style="display:none;" required multiple accept="images/*" onchange="preview_image()">
</form>
And there is a submit button below.
In my jquery part
$('#submit').on('click', function(e) {
var files = $('#file_upload')[0].files;
var form_data = new FormData();
form_data.append("file_upload",files);
$.ajax({
url:"execute/Script.php?request=submit",
type: "POST",
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode == 1){
alert("Success!");
}
}
});
});
And in my script.php
if($_GET['request']=="submit"){
$gallery_G = "";
foreach($_FILES['file_upload']['error'] as $key => $error){
if($error==UPLOAD_ERR_OK){
$tmp_name = $_FILES['file_upload']['tmp_name'][$key];
$PhotoName = $_FILES['file_upload']['name'][$key];
move_uploaded_file($tmp_name,"../img/properties/$name");
$gallery_G = $gallery_G.';'.$PhotoName;
}
}
$sql = mysqli_query($conn,"INSERT INTO property(photos) VALUES('$gallery_G')");
if($sql) {
echo json_encode(array("statusCode"=>1));
}
else{
echo json_encode(array("statusCode"=>2));
}
}
But it returns me this:
Notice: Undefined index: file_upload in G:\Xampp\htdocs\execute\Script.php on line 31
Warning: Invalid argument supplied for foreach() in G:\Xampp\htdocs\execute\Script.php on line 31
{"statusCode":2}
Is there any solution? I need to send those photos using 'append' method. And need to get those photos in 'Script.php' so that I can process or upload them from there.
CodePudding user response:
Try passing the form element to FormData. No need to call the append method afterwards.
var files = $('form')[0];
var form_data = new FormData(files);
By using the append() method, you are putting a [object FileList]
in the $_POST array under the file_upload
key
If you just want the files from the form, you would need a loop:
var files = $('#file_upload')[0].files;
var form_data = new FormData();
for (var i = 0; i < files.length; i ) {
form_data.append("file_upload[]",files[i]);
}