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

Asked

Viewed 96 times

0

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

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

I got it from 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] => {}
)

And that way, I can’t access the properties of array file.

1 answer

0

Turns out you’re not picking up the files via Ajax to be uploaded.

The right way to get them back is like this:

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

That is, you load all the files in the variables and create only one Formdata and use the append function to add all the information you want to get in 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 would be embedded in the formCadEmp, formConfNFe and formConfEmail keys of the $_POST array.

I hope I’ve helped!

  • Hello @Brunofoller: Uncaught TypeError: Cannot read property '0' of undefined.

  • Apologizing. $('#formCadEmp').prop('files')[0]; is the id of the field that receives the file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.