How do you upload file(s) with AJAX

223 Views Asked by At

I am currently trying to upload a file through a form I made, using jQuery. This is what I am attempting to do:

    function ajax_upload(){
    var formData = new FormData($('form#userform'));
        $.ajax({
        url: location.protocol + "//" + location.host + "/profile/uploadPicture",
        dataType: 'json',
        data: formData,
        type: 'post',
        success: function(data, status){
        if (data.status == 'error') {
            $('#error').html(data.msg);
        }
        else {
            var filename = location.protocol + "//" + location.host + "/data/profiles/" + data.msg;

            $('input#filename').val(filename);
            close_upload_form();
            pop_profilechanger(filename);

        }
    }
});
    return false;

}

the form appears to post to the backend, but while trying to return the filename from the uploaded file in a JSON object like: echo json_encode(array('status' => $status, 'msg' => $msg));

Is there something wrong? Please tell me

1

There are 1 best solutions below

0
On

This is how I do it. If you want more information, rather than just my pasted code, check out this http://www.html5rocks.com/en/tutorials/file/dndfiles/ because my code was made for drag and drop files

        handleFiles : function(files, evt, target)
        {
            console.log(target);
            $.each(files, function(index, value)
            {
                var file = value;

                reader = new FileReader();
                reader.onload = function(evt)
                {
                    var li = $("<li class='uploading'><img data-image-id='0' src='" + evt.target.result + "' /></li>");
                    target.find('.imagesList').append(li);

                    var request = new XMLHttpRequest();
                    var formData = new FormData();
                    formData.append('image', file);

                    request.open("Post", settings.uploadImageUrl);
                    request.addEventListener("load", function(evt)
                    {
                        var id = evt.target.responseText;
                        li.removeClass('uploading');
                        li.find('img').attr('data-image-id', id);

                    }, false);
                    request.send(formData);
                };

                reader.readAsDataURL(value);

            });
        },