AJAX upload images from array to process with PHP - javascript

I have a simple form so you can upload images. I store the uploaded images' properties in a array but I want to post this array to a PHP file using ajax. If I try to get the uploaded image: $_FILES['image1'], it returns an empty array. Any idea what I am doing wrong?
PS: It is important to store the images' properties in a array and pass it to a FormData.
var foo = []; var input = document.getElementById('input');
document.getElementById('add').addEventListener('click', () => {
foo.push(input.files[0]);
});
document.getElementById('check').addEventListener('click', () => {
console.log(foo);
});
document.getElementById('upload').addEventListener('click', () => {
var fd = new FormData();
for (let i = 0; i < foo.length; i++) {
fd.append('image'+i, foo[i]);
}
$.ajax({
enctype: "multipart/form-data",
type: "POST",
url: "path/to/php.file",
data: fd,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) { console.log(data); },
error: function (err) { console.log(err); }
});
});
<button id="add">ADD</button>
<button id="check">CHECK</button>
<button id="upload">UPLOAD</button>
<br><br>
<input type="file" id="input" placeholder="UPLOAD IMAGE">
And the PHP file:
<?php
$arr = array();
array_push($arr, $_FILES);
die(json_encode($arr));
?>

Or you need to check php.ini and check if the size of all the images you add exceeds "upload_max_filesize"

I executed the code with two files. It seems that you can print the files successfully with the following code (PHP file)
print_r($_FILES['image0']);
print_r($_FILES['image1']);
I used jquery 3.5.1, for the ajax call.
I hope it helps.

Related

Upload files when it selected

I am trying to make an input field. I want it when I select files, it automatically uploads them without pressing any upload button. here is my code. not mentioning the CSS because it is irrelevant. but if you need it I'll provide it.
//html
<!-- some codes here-->
<input type="file" id="fileUpload" multiple="true" />
<!-- some codes here-->
//javascript
$(document).ready(() => {
$("#fileUpload").on("change", (e)=>{
var formData = new FormData();
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
formData.append("file[]", files[i]);
}
uploadFormData(formData);
});
function uploadFormData(form_data) {
$.ajax({
url: ".uploader.php",
method: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#filenames").html(data);
$(".alert-container div").removeClass("alert-box alert-err");
$(".alert-container div").addClass("alert-box alert-ok");
$("#alertCheck").prop( "checked", true );
setTimeout(()=>{
$("#alertCheck").prop( "checked", false );
}, 5000);
},
error: function (data) {
$(".alert-container div").removeClass("alert-box alert-ok");
$(".alert-container div").addClass("alert-box alert-err");
console.log("err");
},
});
}
});
The issue is due to the way you're accessing the files collection from the event. The code you're using right now works for custom jQueryUI event handlers, yet you're using a standard change event handler. As such you need to change this line:
var files = e.originalEvent.dataTransfer.files;
To this:
var files = e.target.files;
Does this work?
var files = $("#fileUpload").prop('files');

File uploade with additional Data (Javascript, PHP)

I want to uploade a file and send additional data (an array) to the php script.
Here is the HTML and the Javascript Code:
<input type="file" name="fileinput" id="fileinput">
<button class="btn btn-primary" id="btnupload">upload</button>
<script>
$('#btnupload').click(function(){
var formData = new FormData();
formData.append("MacsToChangeImage", selectedMACs.toString()); //selectedMACs is the array which i want to send
formData.append("userfile", $('#fileinput').files[0]);
$.ajax({
url: "ChangeImagesFunction.php",
type:'POST',
data: formData,
processData: false,
cententType: false,
success: function(data)
{
alert('success' + data);
},
error:function(response){
alert(JSON.stringify(response));
}
});
});
</script>
And here ist the PHP Code:
if(!empty($_FILES)) {
$target_dir = "img/epd_uploads/";
$temporaryFile = $_FILES['userfile']['tmp_name'];
$targetFile = $target_dir . $_FILES['userfile']['name'];
if(!move_uploaded_file($temporaryFile,$targetFile)) {
echo "Error occurred while uploading the file to server!";
}else{
if (isset($_POST['MacsToChangeImage'])){
//Name of the Uploaded File
$ChangeImageToPHP = $_FILES['userfile']['name'];
//Get the Array
$MacsToChangeImageStr = $_POST['MacsToChangeImage'];
$MacsToChangeImagePHP = explode(",",$MacsToChangeImageStr);
}
}
}
I think the HTML and Javascript part is fine so far. But i am uncertain how to handle the PHP part. What am i doing worng/missing?
Are there other ways to achieve what im plannig to do?
Thank you in advance

File upload not working in PHP , $_POST['file'] , not able to extract file

I have the following HTML code:
<form action="mail/filesend.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data" validate>
<div class="input-wrpr">
<input type="file" name="files[]">
</div>
<button type="submit">
Send File
</button>
</form>
And then the following file upload code in jQuery:
$(function () {
let files = null;
$('input[type="file"]').on('change' , (e) => {
files = e.target.files;
});
$('form').submit(function(e){
e.stopPropagation();
e.preventDefault();
let data = new FormData();
// files = $('input[type="file"]')[0].files;
$.each(files, function(key, value){
data.append(key, value);
});
console.log(data.getAll('0'));
// console.log(data);
$.ajax({
type: $(this).attr('method'),
url : $(this).attr('action'),
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
data : data
}).done(function(data){
// console.log(data);
if (! data.success) {
// console.log(data.errors);
/*for(let er in data.errors) {
console.log(data.errors[er])
}*/
console.log(data);
} else {
/* else condition fires if form submission is successful ! */
console.log(data.file);
}
}).fail(function(data){
console.log(data);
});
});
});
And the following PHP code for testing :
<?php
// You need to add server side validation and better error handling here
$data = array();
if(isset($_FILES['files'])) {
$data = array('file' => 'I a in if');
}
else {
$data = array('file' => 'I am in else');
}
echo json_encode($data);
?>
Now when i check my console i see that the PHP if condition is not passing , that is it is unable to detect:
isset($_POST['files'])
Why is this happening ? I have tried using isset($_FILES['files']), also I have tried renaming my html file input field to just files instead of files[] , but this does't seem to work , What am I doing wrong ?
I was following the tutorial HERE. But somehow the example I have created just does't work.
Try to print_r($_FILES) and check if it shows an array of file,
If it does, use the same key in $_FILES['same_key_here'] and it supposed to work,
Let me know if it doesn't
If you want to send files, do something like this.
This may help you.
var fileInput = $("#upload_img")[0]; // id of your file
var formData = new FormData();
formData.append("image_file",fileInput.files[0]); //'xmlfile' will be your key
Check in your php code like,
echo $_POST['image_file'];

Upload files in an array differently in jquery ajax

I have this html
<input type="file" name="[]" multiple />
Now I want to upload each of the files separately but I am really stuck.
$('input:file').on('change', function(){
allFiles = $(this)[0].files;
for(var i = 0; allFiles.length > i; i++){
eachFile = allFiles[i];
$.ajax({
url: link,
type: "POST",
data: new FormData(eachFile),
contentType: false,
processData:false,
success: function(result){
console.log(result);
}
})
}
})
But I don't seem to work. I use the above ajax request to upload files in an array but I want to upload them differently. Any suggestion on how to achieve this?
This is not a duplicate to the supposed duplicate question. I want to upload multiple files separately to the server but the question marked wants to upload multiple files at once. I use my above code to upload multiple files to the server at once an it works fine. So why should I as what I already have a solution to?
Use this... Tested (in chrome) and working
$('input:file').on('change', function(){
allFiles = $(this)[0].files;
for(var i = 0; allFiles.length > i; i++){
var eachFile = allFiles[i],
fileData = new FormData();
fileData.append('file', eachFile);
$.ajax({
url: link,
type: "POST",
datatype:'script',
data: fileData,
contentType: false,
processData:false,
success: function(result){
console.log(result);
}
})
}
})

send file using ajax with other type of input

i already had a form which uses ajax to save the the data to the database. so i have this sample
Html code
<input id="product_name" type="text" >
<input id="product_description"/>
<input id="product_img" type="file" accept="image/*"/>
<button id="btnSave">Save</button>
Javascrip Code
$("#btnSave").click(function(){
p_name = $("#product_name").val();
p_des = $("#product_description").val();
p_image = $("#product_img").prop('files')[0];
data = {
'product_name':p_name,
'product_description':p_des
}
$.post('url_here',data,function(response){
console.log(response);
});
});
i do have this info Jquery input.files equivalent but i cant make it passed as a $_FILE for php.Please give me some example codes combining the input type text and file without using the form tag and using jquery ajax.
You can use FormData:
document.getElementById('btnSave').addEventListener('click', function() {
var fd = new FormData();
fd.append('product_name', document.getElementById('product_name').value);
fd.append('product_description', document.getElementById('product_description').value);
fd.append('product_name', document.getElementById('product_img').files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url_here');
xhr.addEventListener('load', function(e) {
console.log(xhr.responseText);
});
xhr.send(fd);
});
UPDATE
Since you want to use jQuery AJAX (I have no idea why, since it was not prepared to use XHR2), you can workaround by telling it to not process the data parameter, e.g:
$('#btnSave').click(function() {
p_name = $('#product_name').val();
p_des = $('#product_description').val();
p_image = $('#product_img').prop('files')[0];
var data = new FormData();
data.append('product_name', p_name);
data.append('product_description', p_des);
data.appned('product_img', p_image);
$.ajax({
url: 'url_here',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(response){
console.log(response);
}
});
});

Categories