V
V
Vadim2015-09-27 18:41:12
PHP
Vadim, 2015-09-27 18:41:12

How to submit using jquery ajax a file along with form data?

And hello again friends! And again zaparka with jquery. There is a form to add some data and a file. I took the plugin for adding a file from this friend, the demo is there:

https://github.com/danielm/uploader

That's all you need and that's enough. I know that there is cooler, but I'll deal with it as soon as there is too much time:

https://blueimp.github.io/jQuery-File-Upload/

In general, I took the first option, I liked the debug console very much besides.
I remade a little demo for myself, translated everything into Russian. And the task is the following:

The data from the form will be added to the database along with a link to the image. The name of the image file will be made up of this form data. But I just can’t send it all in one request, if it’s possible, then I don’t have enough knowledge of jquery and ajax.

I started building a bike.

$(".cloth_add").submit(function() {
    $.ajax({
        type: "POST",
        url: "upload.php",
        data: $(".cloth_add").serialize(),
        cache: true,
        success:
            function processData(data) {
            fileUpload('#cloth-upload', 'upload.php', 1, data);
            alert(data);
        }
    });
    return false;
});


Here it sends the data from the form to the file handler, from there it returns the file name combined from the POST post, and passes it as a parameter to the function. The first parameter is the div block, the second is the handler, the third is the number of valid files, and the last is the filename that will represent the very first key of the $_FILES array. These parameters are already passed to the function that calls the plugin itself, looks like this:

function fileUpload (block, handler, numberOfFiles, filename) {
$(document).ready(function() {
    $(block).dmUploader({
        url: handler,
        maxFiles: numberOfFiles,
        fileName: filename,
        dataType: 'html',
        allowedTypes: 'image/*',
        onInit: function(){
            $.fileUpload.addLog('#upload-debug', 'default', 'Готов к загрузке');
        },
        onBeforeUpload: function(id){
            $.fileUpload.addLog('#upload-debug', 'default', 'Началась загрузка файла #' + id);

            $.fileUpload.updateFileStatus(id, 'default', 'Загрузка...');
        },
        onNewFile: function(id, file){
            $.fileUpload.addFile('#upload-files', id, file);

            /*** Begins Image preview loader ***/
            if (typeof FileReader !== "undefined"){

                var reader = new FileReader();

                // Last image added
                var img = $('#upload-files').find('.upload-image-preview').eq(0);

                reader.onload = function (e) {
                    img.attr('src', e.target.result);
                }

                reader.readAsDataURL(file);

            } else {
                // Hide/Remove all Images if FileReader isn't supported
                $('#upload-files').find('.upload-image-preview').remove();
            }
            /*** Ends Image preview loader ***/

        },
        onComplete: function(){
            $.fileUpload.addLog('#upload-debug', 'default', 'Все загрузки завершены');
        },
        onUploadProgress: function(id, percent){
            var percentStr = percent + '%';

            $.fileUpload.updateFileProgress(id, percentStr);
        },
        onUploadSuccess: function(id, data){
            $.fileUpload.addLog('#upload-debug', 'success', 'Загрузка файла #' + id + ' завершена');

            $.fileUpload.addLog('#upload-debug', 'info', 'Получен ответ от сервера для файла #' + id + ': ' + JSON.stringify(data));

            $.fileUpload.updateFileStatus(id, 'success', 'Загрузка завершена');

            $.fileUpload.updateFileProgress(id, '100%');
        },
        onUploadError: function(id, message){
            $.fileUpload.updateFileStatus(id, 'error', message);

            $.fileUpload.addLog('#upload-debug', 'error', 'Не удалось загрузить файл #' + id + ': ' + message);
        },
        onFileTypeError: function(file){
            $.fileUpload.addLog('#upload-debug', 'error', 'File \'' + file.name + '\' Файл не является изображением и не может быть добавлен');
        },
        onFileSizeError: function(file){
            $.fileUpload.addLog('#upload-debug', 'error', 'File \'' + file.name + '\' Файл не может быть добавлен так как превышен допустимый размер');
        },
        onFallbackMode: function(message){
            $.fileUpload.addLog('#upload-debug', 'info', 'Браузер не поддерживается(попробуйте сделать следующее!): ' + message);
        }
    });
});
}


The plugin itself did not fit, but it is not big, you can see the link to the github:

https://github.com/danielm/uploader/blob/master/sr...

Everything is sent there by this request:
// Ajax Submit
        $.ajax({
            url: widget.settings.url,
            type: widget.settings.method,
            dataType: widget.settings.dataType,
            data: fd,
            cache: false,
            contentType: false,
            processData: false,
            forceSync: false,
            xhr: function(){
                var xhrobj = $.ajaxSettings.xhr();
                if(xhrobj.upload){
                    xhrobj.upload.addEventListener('progress', function(event) {
                        var percent = 0;
                        var position = event.loaded || event.position;
                        var total = event.total || e.totalSize;
                        if(event.lengthComputable){
                            percent = Math.ceil(position / total * 100);
                        }

                        widget.settings.onUploadProgress.call(widget.element, widget.queuePos, percent);
                    }, false);
                }

                return xhrobj;
            },
            success: function (data, message, xhr){
                widget.settings.onUploadSuccess.call(widget.element, widget.queuePos, data);
            },
            error: function (xhr, status, errMsg){
                widget.settings.onUploadError.call(widget.element, widget.queuePos, errMsg);
            },
            complete: function(xhr, textStatus){
                widget.processQueue();
            }
        });
    };

    $.fn.dmUploader = function(options){
        return this.each(function(){
            if(!$.data(this, pluginName)){
                $.data(this, pluginName, new DmUploader(this, options));
            }
        });
    };


The point is this: for sure, you can send everything together - both the file and the form in one request, without building bicycles. The form itself is not big, you can just return the array key and here is the name of the new file! And then it will be necessary to disassemble a large form in parts, and here it will not work. Dear java script experts! Please help modify this plugin to send everything in one request. Well, or two, but so that the data comes at the same time, because. the first POST data sent by the time the file arrives at the server no longer exists.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim, 2015-09-27
@J01

I figured out something, there is such an option there:

extraData: {
  varName:1,
  varName:'string'
}

in principle, you can add as many keys and values ​​​​to it as you like, and it just gets into the $_POST array. So all the same, the developer provided for such an opportunity.
The only thing is that varName is a key, and 'string' is a value, which means that an array gets into the post, inside of which there is already data received from the form. It turns out that they were intended to be sent by post and prepared for this, and once in another array, the ampersand already loses its meaning. As I understand it, the data is added here:
// Append extra Form Data
    $.each(widget.settings.extraData, function(exKey, exVal){
      fd.append(exKey, exVal);
    });

fd is formData
Maybe someone knows how to make the data from the form added here in its pure form?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question