Home >Backend Development >PHP Tutorial >Why Isn't My jQuery AJAX File Upload to PHP Working?
jQuery AJAX File Upload with PHP
Issue:
An AJAX file upload is attempted using jQuery and PHP, but the file is not being uploaded, and the success alert is not triggered.
Solution:
Server-Side Script:
A PHP script on the server is required to handle the file upload, receive the form data, and save the file in the specified location. For example:
if (0 < $_FILES['file']['error']) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']); }
Ensure that the uploads directory has write permissions.
AJAX Call:
The AJAX call in the jQuery script should specify the URL of the server-side script to handle the file upload:
$.ajax({ url: 'upload.php', // Point to the server-side PHP script dataType: 'text', // Specify the expected response type (optional) cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(php_script_response) { alert(php_script_response); // Display the response from the PHP script (optional) } });
Renaming File on the Server:
Instead of $_FILES['file']['name'], use your own server-generated filename in move_uploaded_file() to rename the file:
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/my_new_filename.whatever');
Additional Tips:
The above is the detailed content of Why Isn't My jQuery AJAX File Upload to PHP Working?. For more information, please follow other related articles on the PHP Chinese website!