Upload image on server Ajax serialize and PHP [duplicate]

1

Good afternoon friends, I'm making a website that the person does the registration in my form and I, using AJAX, play the data in the bank. I wanted to know how to save this image that the person put in the form in some variable, so that my upload function can use it as soon as it is registered. For example:

function saveCliente(){
    $.post("../setters/addLojaPainel.php", $('#form').serialize(), function (response) {
        if (response.result == "1") {
            doUpload(response.id);
            getData();
        }else{
            alert(response.exception);
        }
    });
}

that is, when the result of the request is 1 (success) it uses doUpload, function to store the image on the server, using another request data. However, I do not know how I store the image that is in the form.

I hope it was clear, is that the code is very extensive and it would not be possible to paste here. Thankful

    
asked by anonymous 08.12.2015 / 19:18

1 answer

0

The serialize function for forms is only able to serialize data that is not of type file

To upload the image, you will need to work around this by changing how the $.ajax function treats the data:

upload without refresh with FormData, jquery

If you prefer, I still have a ready solution in gist to solve this problem:

link

I'll post the code here because of the site's recommendation not to rely solely on outside links:

(function ($) {

    var defaults = {
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        onProgress: new Function,
        xhr: function (xhr) {

            var xhr = $.ajaxSettings.xhr();

            xhr.upload.addEventListener('progress', function(e) {
                var percent = parseFloat(((e.loaded / e.total) * 100).toFixed(2));

                defaults.onProgress(percent, e);

            }, false);

            return xhr;
        },

    };

    $.fn.ajaxUpload = function (options) {

        var formData = new FormData;

        // if element is a form, find all inputs 

        if (this.is('form')) {

            var $el = this.find(':input');

        } else {

            var $el = this;
        }

        $el.each(function() {

            var $that = $(this);

            var name = $that.attr('name');

            var files = $that.prop('files');

            var value = $that.val();

            if (!name) return;

            // when input not has file, we know that is a common input

            if (!files) {

                formData.append(name, value);

            } else {

                // Handles single file or multiple file

                $.each(files, function(i, file) {
                    formData.append(name, file)
                });
            }
        })

        options = $.extend(defaults, options, {
            data: formData
        });

        $.ajax(options);
    }

})( jQuery );
    
09.12.2015 / 13:49