how to queue file uploading in ajax jquery? - javascript

<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.

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

Uploading multiple files from different inputs using Ajax

I have two different file inputs and multiple textual/select inputs, that I'd like to upload to a PHP file using Ajax. The file inputs are meant to send images, and because they are two specific images that I'd like to identify by the name of the input, I do not want to use <input type="file" multiple>.
Currently I have the following (names have been changed to keep it simple):
<input type="file" name="file1">
<input type="file" name="file2">
<textarea name="text1"></textarea>
<button>Submit</button>
What I have tried is to push both to a variable once the change event of the file input gets fired, followed by the button press triggering the upload using Ajax.
$('input[type="file"][name="file1"]').on('change', prepareUpload);
$('input[type="file"][name="file2"]').on('change', prepareUpload);
files = new Array;
function prepareUpload(event){
files.push(event.target.files);
}
$('button').on('click', uploadFiles);
function uploadFiles(event){
$('#uploadInfo').html('Uploading...');
event.stopPropagation();
event.preventDefault();
var data = new FormData();
$.each(files, function(key, value){
data.append(key, value);
});
data.append('text1', $('textarea[name="text1"]').val());
$.ajax({
url: '',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
//do stuff
},
error: function(error){
console.log(error);
}
});
}
But this seems to do nothing. Is it even possible to append two image inputs to the same request using Ajax, or am I better off trying to put it in two different requests?
event.target.files is a array, so you need the first file in the array
function prepareUpload(event){
files.push(event.target.files[0]);
}

Return PHP Variable to Jquery

I have a page called index.php where I have some forms where the user must input information.
On this page I have this JQuery functions.
else if (result == 3)
{
jQuery.get('sample.txt', function(data) {
alert(data);
});
}
where the file sample.text its shown on an alert.
But, I have a page called download.php. When the user click on "submit" at page "index.php" , its send to the page "download.php", the values sent using Ajax POST.
var formData = new FormData($('#form_principal')[0]);
$("#loading").show();
setTimeout(function() {
$.ajax({url: "/tkclientespdo/etiquetaslog/000/0000/download.php",
type: "post",
data: formData,
cache: false,
async:true,
contentType: false,
processData: false,
success: function(result)
on page "download.php" i have this variable :
$horaenvio = date("dmYGis");
after this variable i have a code :
echo 3;
that return the function at index.php .
but i wanna change 'sample.txt" for the variable "$horaenvio".
someone could help.
You can use localStorage and storage event or SharedWorker to store the value data at index.php, and get the value at download.php, then .append() data to the FormData object, then echo the proper POST value.

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/

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

Categories