cianz
cianz

Reputation: 159

Use jQuery AJAX to upload a file via FormData

I want to upload a single file using just jQuery and then replace the upload form with the output from the PHP script that has processed the file upload.

Currently after I click submit, I receive a blank response from the PHP script. I think it's because the form data (file and upload inputs) is being overwritten by the upload data?

Any help solving this is much appreciated!

Here is my code:

HTML

<div id="container">
    <form id="form" enctype="multipart/form-data">
        <input name="file" type="file">
        <input type="hidden" name="upload">
    </form>
    <a href="javascript:void(0)" onclick="uploadData($('#form').serialize(), 'upload.php', '#container'); return false;">Upload &gt;</a>
</div>

JavaScript

function uploadData(data, url, container) {

    var formData = new FormData($(data)[0]);

    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function(response) {
            $(container).html(response);
        },
        error: function() {
            alert('Error!');
        },
    });

    return false;
};

PHP

if (isset($_POST['upload'])) {

    // check the file has been uploaded
    if (isset($_FILES['file'])) {

        // check if there was an error uploading the file
        if ($_FILES['file']['error'] > 0) {

            // display error
            echo 'Error: ' . $_FILES['file']['error'];
        } else {

            // move and store file (overwrite if it already exists)
            $fileName = '/upload/' . $_FILES['file']['name'];
            move_uploaded_file($_FILES['file']['tmp_name'], $fileName);

            echo 'File uploaded successfully';
        }
    } else {

        die ('Error: No file selected for upload');
    }

}

Upvotes: 1

Views: 7733

Answers (1)

Marcelo Pascual
Marcelo Pascual

Reputation: 820

I don't think ajax can handle file uploads. Have you checked that the file is actually uploaded?

If it is true, your response is empty because isset($_POST['upload']) returns false. Try adding a last else statement, to check what I'm saying:

if (isset($_POST['upload'])) {
    ...
} else {
    die ('Error: AJAX cannot handle file uploads');
}

Upvotes: 1

Related Questions