Home > Backend Development > PHP Tutorial > How to Implement jQuery AJAX File Uploads with PHP?

How to Implement jQuery AJAX File Uploads with PHP?

Linda Hamilton
Release: 2024-12-23 22:48:17
Original
788 people have browsed it

How to Implement jQuery AJAX File Uploads with PHP?

jQuery AJAX File Upload with PHP

To successfully implement file uploads with minimal setup, follow these steps:

Client-Side (jQuery)

  1. Update the jQuery script as follows:
$('#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', // Point to the server-side PHP script
        dataType: 'text', // Expect text back from the PHP script
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'post',
        success: function(php_script_response) {
            alert(php_script_response); // Display any response from the PHP script
        }
    });
});
Copy after login

Server-Side (PHP)

  1. Create a PHP script named upload.php:
<?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 Notes:

  • Ensure the uploads directory is writeable on the server.
  • Adjust the file path in the move_uploaded_file() function to match the server-side location of the uploads directory.
  • Configure upload_max_filesize and post_max_size in your PHP settings to accommodate the file size.

The above is the detailed content of How to Implement jQuery AJAX File Uploads with PHP?. 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