How to adpate upload with Ajax [duplicate]

4

I'm trying to adapt an upload that I have using Ajax , but I'm not getting it, so I read I need to use formData , tried some alternatives, but all did not work, my form has several fields and what I'm with problem is just uploading.

What I have right now is this:

The form

<form enctype="multipart/form-data" class="form-horizontal" id="frmDoc" method="POST">
<div class="form-group">
  <label class="col-md-2 control-label">Arquivo</label>
  <div class="col-md-10">
    <input type="file" class="btn btn-default" id="Arquivo"  name="Arquivo">
    <p class="help-block"> Extensão permitida <strong>PDF</strong>. </p>
  </div>
</div>

The submission Ajax :

$(document).ready(function(){
    $(function () {
        // Validation
        $("#frmDoc").validate({
            // Do not change code below
            errorPlacement: function (error, element) {
                error.insertAfter(element.parent());
            },
            submitHandler: function (form) {

                var data = $(form).serialize();

                // console.log(data);

                $.ajax({
                    type: 'POST',
                    url: 'pDocsNormativos.php',
                    data: data,
                    dataType: 'json',
                    beforeSend: function () {
                        $("#msgInsert").html('×AVISO! Enviando...');
                    },
                    success: function (response) {
                        if (response.codigo == "1") {
                            $("#msgInsert").html('×AVISO!' + response.mensagem  + '');
                        } else {
                            $("#msgInsert").html('×ATENÇÃO! ' + response.mensagem + '');
                        }
                    //  $('#frmDoc').each (function(){
                    //      this.reset();
                    //  });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        console.log(xhr, ajaxOptions, thrownError);
                        $("#msgInsert").html('×ATENÇÃO! Ocorreu um erro ao tentar enviar o Documento. Contate o suporte técnico.');
                    }
                });
                return false;
            }
        });
    });
});

I saw some examples but I could not adapt, such as this link: Upload file with AJAX

The file field is not being sent, see console.log() :

    
asked by anonymous 19.12.2016 / 16:17

1 answer

1

Hello @adventistapr

You'll need to set cache:false, contentType: false, processData: false to $.ajax() setting and use FormData .

This way you will be able to send the files and other form fields.

$(document).ready(function(){
    $(function () {
        // Validation
        $("#frmDoc").validate({
            // Do not change code below
            errorPlacement: function (error, element) {
                error.insertAfter(element.parent());
            },
            submitHandler: function (form) {
                /*
                  Você pode usar também o 
                  var myForm = document.getElementById('frmDoc');
                  var data = new FormData(myForm);
                */
                var data = new FormData(form[0]);

                // console.log(data);

                $.ajax({
                    type: 'POST',
                    url: 'pDocsNormativos.php',
                    data: data,
                    dataType: 'json',
                    cache: false,//<--- Define como falso
                    contentType: false,//<--- Define como falso
                    processData: false,//<--- Define como falso
                    beforeSend: function () {
                        $("#msgInsert").html('×AVISO! Enviando...');
                    },
                    success: function (response) {
                        if (response.codigo == "1") {
                            $("#msgInsert").html('×AVISO!' + response.mensagem  + '');
                        } else {
                            $("#msgInsert").html('×ATENÇÃO! ' + response.mensagem + '');
                        }
                    //  $('#frmDoc').each (function(){
                    //      this.reset();
                    //  });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        console.log(xhr, ajaxOptions, thrownError);
                        $("#msgInsert").html('×ATENÇÃO! Ocorreu um erro ao tentar enviar o Documento. Contate o suporte técnico.');
                    }
                });
                return false;
            }
        });
    });
});

See some references:

link

link

link

    
13.01.2017 / 14:18