Reputation: 2654
I have a dialog box.The users have the option to upload files. I want to upload the files to server on clicking the button within the jquery dialog.I have tried many codes but unfortunately ,I cannot find the solution.Please help me.
My fiddle fiddle
Jquery:
$(function(){
$(document).on('click','.click_link',function(){
$("#dialog_loader").dialog("open");
$("#dialog_loader").css({'display':'show'});
return false;
});
$("#dialog_loader").dialog({resizable: false,
height:"auto",
modal: true,
minWidth: 400,
autoOpen:false,
position: 'center top',
buttons: {
"Update": function() {
var form_data = new FormData();
$.each($("input[type='file']")[0].files, function(i, file) {
form_data.append('file', file);
});
form_data.append("status", 'update');
$.ajax({
url:path,
type:'POST',
dataType: "HTML",
contentType : false,
processData : false,
data:form_data,
success:function(msg){
if(msg==1)
{
alert(123);
}
}
});
},
"Approve":function(){
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
$(document).on('click','.add_more',function(e){
e.preventDefault();
var filePresent = document.getElementsByClassName('file')[document.getElementsByClassName('file').length-1].files.length;
if(filePresent >0 ){
$(this).parent().find('#extra_file_div').find('.file_div_child').append("<br/><input name='file_uploads[]' type='file' class='multi_files file' /><button class='remove'>X</button>");
//$(this).before("<div class='file_div_child'><input name='file_uploads[]' type='file' class='multi_files file' /><button class='remove'>X</button></div>");
}
});
$(document).on('change','input:file',
function(){
$('input:file').removeClass('multi_files');
if ($(this).val()) {
if($(this).parent().parent().find('.remove').length <1)
{
$(this).after("<button class='remove first_remove' >X</button>");
}
$('.add_more').show();
}
else
{
$('.add_more').hide();
}
});
$(document).on('click','.remove',function(){
var length = $('#dialog_attachments').find(".file").length;
if(length > 1 ){
$(this).prev('input:file').remove();
$(this).prev('br').remove();
$(this).remove();
}
else
{
$(".file").val('');
$(this).remove();
$(this).parent('.file_div_child').find('br').remove();
$('.add_more').hide();
}
return false;
});
});
Upvotes: 1
Views: 1831
Reputation: 33
let form_data = new FormData();
$.each($("input[type='file']")[0].files, function(i, file) {
form_data.append('file[]', file);
})
Upvotes: 0
Reputation: 2654
I have created a form and put the file input parts inside that form element. Then using jquery each function,I have added each file inputs to form_data object.
var form_data = new FormData();
var inputs = $(document).find("#file_form input");
$.each(inputs, function (obj, v) {
$.each($(v)[0].files, function(i, file) {
form_data.append(v.name, file);
});
});
form_data.append("status", 'update');
I have updated the fiddle.
Upvotes: 0