0

I am working on a multiple file uploader using HTML5's FormData and jQuery. I have the following code:

$(function() {
    $('#file').bind("change", function() {
        var formData = new FormData();
        //loop for add $_FILES["upload"+i] to formData
        for (var i = 0, len = document.getElementById('file').files.length; i < len; i++) {
            formData.append("file" + i, document.getElementById('file').files[i]);
        }

        //send formData to server-side
        $.ajax({
            url : "file-upload.php",
            type : 'post',
            data : formData,
            dataType : 'json',
            async : true,
            processData: false,  // tell jQuery not to process the data
            contentType: false,   // tell jQuery not to set contentType
            error : function(request) {
                alert('error!!');
                console.log(request.responseText);
            },
            success : function(json) {
                alert('success!!');
                $('#upload-result')[0].append(json);
            }
        });
    });
});

I can see that my file-upload.php works fine because the files are uploaded! But why does my jQuery hit the error function and not the success function? I get an alert of Error.

In the console window, I see the result of my PHP echo call! Which I want to append to #upload-result as shown in my success function.

PHP code

foreach($_FILES as $index => $file)
{
    $fileName     = $file['name'];
    // echo '[ file name: ' . $fileName . ' - ';
    $fileTempName = $file['tmp_name'];
    // echo 'file temp name: ' . $fileTempName . ' ]';

    if(!empty($file['error'][$index]))
    {
        // some error occured with the file in index $index
        // yield an error here
        return false; // return false also immediately perhaps??
    }

    // check whether it's not empty, and whether it indeed is an uploaded file
    if(!empty($fileTempName) && is_uploaded_file($fileTempName))
    {
        // the path to the actual uploaded file is in $_FILES[ 'file' ][ 'tmp_name' ][ $index ]
        // do something with it:
        move_uploaded_file($fileTempName, "uploads/" . $fileName);
        echo json_encode('<p>Click <a href="'. 'uploads/' . $fileName . '">here</a> to download file!</p>');
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
J86
  • 14,345
  • 47
  • 130
  • 228

1 Answers1

0

I figured it out. I was getting the jQuery AJAX error even though my status code was 200 for the php file because I had my dataType as JSON, whilst I was returning simple HTML.

dataType: 'html',

Fixed it!

Thanks all.

J86
  • 14,345
  • 47
  • 130
  • 228