-
Notifications
You must be signed in to change notification settings - Fork 77
Description
Hi
for this works awesome for one input file tag file but if more than one file input tag I am not able to upload it ... if I keep the ajax function in a function and call it for each tag
it has three ajax call . Is there any work around for this to reduce it to one ajax call
Below is my code little modified :
jQuery(document).ready(function() {
var files = {};
var filesArr = [];
jQuery('input[type=file]').on('change', prepareUpload);
function prepareUpload(event)
{
var $this = jQuery(this);
if ($this.val() == '') {
Response('- Upload file not selected!', true);
$this.addClass('Error').fadeOut().fadeIn();
return false;
} else {
$this.removeClass('Error');
files = event.target.files;
if(files[0].name){
filesArr.push(files);
}
}
console.log(filesArr);
}
jQuery( "#cmdSubmit" ).on( "click", function() {
var imgVal = jQuery('#image_pe').val();
alert(imgVal);
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
jQuery.each(filesArr, function(key, value)
{
ajaxForm(filesArr[key])
// console.log(filesArr[key]);
});
});
function ajaxForm(files){
// Create a formdata object and add the files
var data = new FormData();
jQuery.each(files, function(key, value)
{
data.append(key, value);
});
jQuery.ajax({
url: '/myphp.php?files',
type: 'POST',
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
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = jQuery(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
jQuery.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
jQuery.ajax({
url: '/myphp.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});