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.
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); } }); });
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']); } ?>
To rename the file on the server using PHP:
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/my_new_filename.whatever');
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!