Upload files in an array differently in jquery ajax - javascript

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);
}
})
}
})

Related

AJAX upload images from array to process with PHP

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.

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');

uploading a file at the same time saving another data's from database codeigniter

i have a question regarding with this situation
I have two forms which consist of #1 Form is an image uploader form and the #2 Form is consist of user data which i want to fire with a one button only using ajax.
Here my problem is about passing the values. How can i make this var formData = new FormData($('#form-upload')[0]);
and
#frm_patientreg
to be something like this: $('#form-upload, #frm_patientreg').serialize(),
Here is my ajax:
var inputFile = $('input[name=file]');
// var uploadURI = $('#form-upload').attr('action');
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
else {
alert("No File Selected");
}
JSFIDDLE :https://jsfiddle.net/ny3rvowo/1/

AJAX form submitting multiple values to MySQL even after using bind unbind, on off

Okay so this problem has been solved multiple times but mine is a bit more complicated. The following is my AJAX which takes as input Text fields and image and submits the fields and file path to the database.
$(function () {
$('form#data').off('submit').on('submit',function () {
var formData = new FormData($(this)[0]);
$.ajax({
type:'POST',
url: 'upload.php',
data: formData,
async:false,
cache:false,
contentType: false,
processData: false,
success: function (returndata) {$('#result').html(returndata);}
});
return false;
});
});
Now when I submitted a file it was uploaded normally. Then if I tried submitting a second file, it created multiple copies on the database. And it went on exponentially increasing as I went on uploading further.
So I looked up and saw that bind/ unbind and on/off were two solutions.
This worked for for the second file uploaded, but from the third file onwards the repetition continued.
Please let me know where i am going wrong.
Thanks.
Okay so I solved it. I removed the on off and did this. Now works fine!
$(function () {
$('form#data').submit(function (e){
e.preventDefault();
e.stopImmediatePropagation();
var formData = new FormData($(this)[0]);
$.ajax({
type:'POST',
url: 'upload.php',
data: formData,
async:false,
cache:false,
contentType: false,
processData: false,
success: function (returndata) {$('#result').html(returndata);}
});
return false;
});
});

how to queue file uploading in ajax jquery?

<script>
funcupload(i) {
var formData = new FormData();
files = $("#upload").get(0).files;
formData.append("upfiles[]", files[i]);
$.ajax({
url:"upload.php",
type: 'post',
data: formData,
cache: false,
processData: false,
contentType: false,
success:function(data) {
alert("Complete");
i++;
}
}
</script>
<input type=\"file\" id=\"upload\" name=\"upfiles[]\" multiple>
<input type=\"button\" value=\"Upload\" name=\"upload\" onclick=\"funcupload(0)\">
I want to queue for upload files. In my above code when first file is uploading, second file is pending status. But if upload button clicked again after select files then first file is starting to upload same time with first file added to the previous click of upload button.
How can queue ajax upload for files Or in other words how can added next files to current ajax?
What I think you want to do:
user select 4 files to upload.
User clicks button
you want to do an ajax-call for each file, but they can't overlap
If that's the case, then you can do this:
var filesToUpload = null;
var uploadNextFile(counter)
{
$.ajax({
url:"upload.php",
type: 'post',
data: files[i],
cache: false,
processData: false,
contentType: false,
success:function(data) {
if (counter < filesToUpload.length)
uploadNextFile(counter++);
else
filesToUpload = null;
}
}
}
Now, when the submit-button is clicked, you call uploadNextfile() and pass the files and counter 0.
If the user adds files, you can check if filesToUpload is empty or not. If it's not empty, you can add the files, and the code will continue running:
filesToUpload.push(/*extra files*/);
If it's empty, you can just call the function again.

Categories