How does using Ajax affect the file upload process in PHP?

When using Ajax for file uploads in PHP, the traditional form submission method is bypassed, which can complicate the handling of file uploads. To solve this issue, you can use a JavaScript FormData object to send the file data asynchronously to the PHP server, where you can process the file upload as usual.

<?php
// Check if file is uploaded via Ajax
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    // Handle file upload
    $file = $_FILES['file'];
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($file['name']);

    if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
        echo 'File uploaded successfully';
    } else {
        echo 'Error uploading file';
    }
}
?>