How to pass, via AJAX, multiple forms with multiple files

0

I have 3 forms on the same page, where each form has inputs of the file type. I need to click on a single button, it is possible to correctly use Ajax to forward all fields (mainly that $ _FILES is available in the PHP page).

I've tried the following:

$('#cadastrar-emp').on('click', function () {
    var form = $('#formCadEmp')[0],
        formII = $('#formConfNFe')[0],
        formIII = $('#formConfEmail')[0];
    var data = new FormData(form),
        dataII = new FormData(formII),
        dataIII = new FormData(formIII);

    data.append('formConfNFe', JSON.stringify(dataII));
    data.append('formConfEmail', JSON.stringify(dataIII));
    jQuery.ajax({
        url: "actions/cadastrar-empresa.php",
        type: 'post',
        enctype: 'multipart/form-data',
        cache: false,
        contentType: false,
        processData: false,
        data: data,
        success: function (data) {}
    });
});

And I got the PHP page:

Array
(
    [razao-social] => 
    [nome-fantasia] => 
    [cnpj] => 
    [estado] => 
    [cep] => 
    [cidade] => 
    [logradouro] => 
    [bairro] => 
    [complemento] => 
    [numero] => 
    [email] => 
    [celular] => 
    [fixo] => 
    [insc-estadual] => 
    [insc-municipal] => 
    [cnae-fiscal] => 
    [reg-trib] => 1
    [formConfNFe] => {}
    [formConfEmail] => {}
)

Being that way, I can not access the properties of array file .

    
asked by anonymous 06.08.2017 / 21:31

1 answer

0

It turns out that you are not picking up files via Ajax to be sent.

The correct way to recover them is like this:

var formCadEmp = $('#formCadEmp').prop('files')[0];

That is, you load all the files into the variables and create only one FormData and use the append function to add all the information you want to get into your PHP.

I would try this way:

var formCadEmp    = $('#formCadEmp').prop('files')[0];
var formConfNFe   = $('#formConfNFe').prop('files')[0];
var formConfEmail = $('#formConfEmail').prop('files')[0];
var dadosForm     = $('#form').serialize();

var form_data = new FormData();

form_data.append('formCadEmp', formCadEmp);
form_data.append('formConfNFe', formCadEmp);
form_data.append('formConfEmail', formCadEmp);
form_data.append('dadosForm', dadosForm);

$.ajax({
    url: url,
    dataType: 'text',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data,
    type: 'post',
    success: function(data){}       
});

In your PHP, the files files would be inside the formCadEmp, formConfNFe, and formConfEmail keys of the $ _POST array.

I hope I have helped!

    
07.08.2017 / 20:08