Home >Backend Development >PHP Tutorial >How to Troubleshoot jQuery AJAX File Uploads with PHP Server-Side Implementation?
The question revolves around implementing a basic file upload functionality on an intranet page using jQuery AJAX and PHP. The user has set up the HTML and jQuery code but encounters issues with uploading the file and saving it in the desired directory. Additionally, they seek advice on renaming the file on the server side.
The jQuery script sends a form containing the uploaded file to a server-side PHP script via an AJAX request. However, the issue lies in the lack of a PHP script on the server to process the file and move it to the specified uploads directory.
Server-Side PHP Script
To rectify the issue, a PHP script named 'upload.php' is required on the server. This script will handle the file upload and perform the necessary operations. Here's the code for the PHP script:
<?php if (0 < $_FILES['file']['error']) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']); } ?>
This PHP script:
In the jQuery script, the URL is modified to point to the 'upload.php' script. Additionally, changing the 'dataType' to 'text' allows for displaying the response from the PHP script if any. The updated script:
$('#upload').on('click', function() { var file_data = $('#sortpicture').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); alert(form_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); } }); });
In the above solution, the uploaded file retains its original name. To rename the file, make the following modification in the PHP script:
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/my_new_filename.whatever');
This line replaces the original file name with 'my_new_filename.whatever' in the 'uploads' directory.
The above is the detailed content of How to Troubleshoot jQuery AJAX File Uploads with PHP Server-Side Implementation?. For more information, please follow other related articles on the PHP Chinese website!