Alex
Alex

Reputation: 9265

submit additional form data jquery file upload

I'm having trouble getting $('.drop').attr('data-id') in formData:

$('.drop').fileupload({
    dataType: 'json',
    url: base_path + 'parallax/upload',
    autoUpload: false,
    replaceFileInput: false, // interferes w/ dropify
    formData: {
        id: $('.drop').attr('data-id'), // nothing
        stmt: '1', // works
        '{/literal}{$this->security->get_csrf_token_name()}{literal}': '{/literal}{$this->security->get_csrf_hash()}{literal}'
    },
    add: function (d, c) {
        console.log($(this).attr('data-id')); // works
        console.log($('.drop').attr('data-id')); // works
        console.log($('#fileupload').attr('data-id')); // works
        var a = [];
        var b = /\.(gif|jpe?g|png)$/i;
        if (c.originalFiles[0]['name'].length && !b.test(c.originalFiles[0]['name'])) {
            a.push('Not an accepted file type.');
        }
        if (c.originalFiles[0]['size'].toString().length && c.originalFiles[0]['size'] > maxsize) {
            a.push('Filesize is too big; try increasing post_max_size and/or upload_max_filesize.');
        }
        if (a.length > 0) {
            bootbox.alert(a.join(''));
        } else {
            start_time = new Date().getTime();
            c.submit();
        }
    },

According to the docs, additional form data can be added via:

$('#fileupload').fileupload({
    formData: {example: 'test'}
});

Which works for my csrf token and other things I manually define, however I cannot seem to get the data-id of the input field in formData. No errors are occurring, but I do see my request being sent without the id attribute - if I manually define it - it works. I can also get the property in the add function.

Whats going on?

Upvotes: 0

Views: 660

Answers (1)

BergListe
BergListe

Reputation: 433

As far as I can see you are trying to add the value of $('.drop').attr('data-id') at the moment you initialize your fileuploadclass. At this time the attribute will most certainly be empty.

Try to set formaData.id prior to the actual upload using the fileuploadsubmit event as described in: https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-form-data#setting-formdata-on-upload-start

$('.drop').bind('fileuploadsubmit', function (e, data) {
    data.formData.id = $('.drop').attr('data-id');       
    //or in your case `this` will work, too:
    //data.formData.id = $(this).attr('data-id');       
});

Upvotes: 1

Related Questions