Home > Backend Development > PHP Tutorial > Why Does My jQuery AJAX File Upload to PHP Fail Despite Showing '[object FormData]'?

Why Does My jQuery AJAX File Upload to PHP Fail Despite Showing '[object FormData]'?

Susan Sarandon
Release: 2024-12-28 03:51:09
Original
853 people have browsed it

Why Does My jQuery AJAX File Upload to PHP Fail Despite Showing

jQuery AJAX File Upload in PHP

Problem: Uploading files through jQuery AJAX request fails despite browser showing "[object FormData]" and an empty "uploads" folder on the server.

Solution: To successfully upload files using jQuery AJAX, a server-side script is needed to handle the uploaded file and move it to the desired location.

Updated jQuery Script

The following updated jQuery script points to a server-side PHP script called "upload.php":

$("#upload").on("click", function() {
    var file_data = $("#sortpicture").prop("files")[0];
    var form_data = new FormData();
    form_data.append("file", file_data);
    $.ajax({
        url: 'upload.php',
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response);
        }
    });
});
Copy after login

Server-Side PHP Script

The following "upload.php" script checks for errors in the uploaded file and moves it to the "uploads" directory:

<?php
if (0 < $_FILES['file']['error']) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
} else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Copy after login

Additional Considerations

  • Ensure you have the correct server path to the "uploads" directory.
  • Make sure the "uploads" directory is writable.
  • Check your PHP configuration for "upload_max_filesize" and "post_max_size" to ensure your test files do not exceed these limits.

Renaming File Using Server-Side Script

To rename the file on the server using PHP:

move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/my_new_filename.whatever');
Copy after login

The above is the detailed content of Why Does My jQuery AJAX File Upload to PHP Fail Despite Showing '[object FormData]'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template