0

I'm trying to upload files through Ajax call and jQuery. Each input[type="file"] is handled dynamically as you will see on the code below and are created on the change event for the Select2 element.

var tipoRecaudo = $('#tipoRecaudo'),
    tipo_recaudo = tipoRecaudo.val(),
    selectedIdsTipoRecaudo = [];

tipoRecaudo.select2({
    ajax: {
        dataType: 'json',
        url: function () {
            return Routing.generate('obtenerRecaudosTramite');
        },
        data: function (tipo_recaudo) {
            return {
                filtro: tipo_recaudo
            }
        },
        results: function (data) {
            var myResults = [];
            $.each(data.entities, function (index, item) {
                if (selectedIdsTipoRecaudo.indexOf(item.id.toString()) === -1) {
                    myResults.push({
                        'id': item.id,
                        'text': item.nombre
                    });
                }
            });
            return {
                results: myResults
            };
        }
    },
    formatAjaxError: function () {
        return Translator.trans('mensajes.msgNoConexionServidor', {}, 'AppBundle');
    }
}).change(function () {
    var id = $(this).val(),
        selectedData = tipoRecaudo.select2("data"),
        htmlTpl = '<table class="table"><caption>'+ selectedData.text + '</caption><tbody><tr><td>';
        htmlTpl += '<input type="hidden" name="tipoRecaudos[]" id="tipoRecaudo ' + id + '" value="' + selectedData.id + '" /><div class="row"><div class="col-xs-6"><div class="form-group"><input type="file" id="recaudosNombreArchivo' + id + '" name="recaudos[nombre_archivo][]" multiple="multiple" class="form-control" /></div></div></div></div>';
        htmlTpl += '</td></tr></tbody></table>';

    selectedIdsTipoRecaudo.push(id);
    $('#recaudoContainer').append(htmlTpl);
});

$('#recaudoContainer').on('change', 'input[type=file]', function (event) {
    $("input:file").filestyle({
        buttonText: "Seleccionar archivo",
        iconName: "fa fa-upload",
        buttonName: "btn-primary"
    });
});

$('#btnGuardarPasoSieteAgregarProducto').on("click", function (event) {
    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // Create a formdata object and add the files
    var formData = $('#formRecaudosTramites').serialize();

    $.each($('#formRecaudosTramites')[0].files, function (key, value) {
        formData = formData + '&recaudos[]=' + value;
    });

    $.ajax({
        url: Routing.generate('rpniSubirRecaudos'),
        type: 'POST',
        data: formData,
        cache: false,
        dataType: 'json',
        contentType: 'multipart/form-data',
        processData: false, // Don't process the files
        //contentType: false // Set content type to false as jQuery will tell the server its a query string request
    }).done(function (data, textStatus, jqXHR) {
        if (typeof data.error === 'undefined') {
            console.log('SUCCESS: ' + data.success);
        } else {
            // do something with error
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        // do something with fail callback
        // STOP LOADING SPINNER
    });
});

What is happening is: no filenames exists on query string, no files are upload or send through the Ajax call, instead it's sending a [object Object], what I'm doing wrong? Can any give me some working code for this stuff?

EDIT:

After reads the post referenced by user I change my code as the one before and now the error turns on:

TypeError: a is undefined
    ...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e...

What is wrong there?

Note: Yes, I know there are tons of plugins for handle this like jQuery File Upload from Blueimp, Dropzone and some others but I leave them out since I start using jQuery File Uploader from inside OneupUploaderBundle on my Symfony2 project and spent 4 days without success so I move to the other side: made things by myself so I can learn something else and improve my knowledge

Community
  • 1
  • 1
ReynierPM
  • 17,594
  • 53
  • 193
  • 363
  • 1
    Sending files requires 'multipart/form-data' request type. Not sure if AJAX can do this out of the box. I guess you want this: http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax – Andrew Dunai Dec 03 '14 at 18:34

1 Answers1

1

i think this will help you,

 var fd = new FormData();
 //name is the key on the page of php to access the file
 fd.append('name', $('#aob_file')[0].files[0]);

 pass this fd object to your data field in ajax,