How to upload with Ajax

Asked

Viewed 259 times

4

I’m trying to adapt an upload I’ve been using Ajax, but I’m not getting it, so I read I need to use the formData, I tried some alternatives, but all of them didn’t solve, my form has several fields and what I’m having trouble with is the upload.

What I have at the moment 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>

Sending 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 could not adapt, example as this link: Upload a file with AJAX

The file field is not being sent, see console.log(): inserir a descrição da imagem aqui

  • 1

    See if this helps: http://answall.com/questions/142834/enviando-uma-imagem-e-outros-dados-via-jquery-para-php

  • What a mistake you’re making?

  • Hello @Localhost, I can’t send the file to upload, when I get to upload it is 'NULL'

  • Is the data before sending going correctly? Like this your file that receives the data for upload?

  • Most form fields are going correctly to the page . php which will upload the file, but the file will not.

1 answer

1


Hello @adventistapr

You will need to define the cache:false, contentType: false, processData: false in the configuration of $.ajax() and use the Formdata.

This way you can 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:

https://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax

https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php

https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

  • Thanks for the tip @Carlos Fernandes, I will test instant.

Browser other questions tagged

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