Home >Web Front-end >JS Tutorial >How to Upload Files Using jQuery AJAX and PHP?

How to Upload Files Using jQuery AJAX and PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 04:23:09769browse

How to Upload Files Using jQuery AJAX and PHP?

jQuery AJAX File Upload with PHP

To enable file uploading on your intranet page, follow these steps:

Client-side (HTML and JavaScript)

Use the following HTML for file selection:

<input>

Update your JavaScript to send the selected file to the server:

$("#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', // Expected response from PHP script
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // Display response from PHP script
        }
    });
});

Server-side (PHP)

Create a PHP script named upload.php to handle the file upload:

<?php

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.

Renaming the Uploaded File

To rename the file during upload, use the following code in the PHP script:

move_uploaded_file(
    $_FILES['file']['tmp_name'],
    'uploads/new_filename.extension'
);

Remember to configure your PHP settings for upload_max_filesize and post_max_size accordingly.

The above is the detailed content of How to Upload Files Using jQuery AJAX and PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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