I have this HTML containing two forms in my-account.php file:
<div class="tab-content">
                                        <div class="tab-pane active" id="overviewTab">
                                            <p>
                                                Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores repellat in accusamus atque culpa sequi ut quod, mollitia quo natus.
                                            </p>
                                            <p class="mb-0">
                                                Temporibus cum obcaecati iste sed natus blanditiis nihil rerum tempore quos itaque mollitia, odit dicta praesentium molestiae. Nostrum eveniet minima commodi consequatur.
                                            </p>
                                        </div>
                                        <div class="tab-pane show" id="profileTab">
                                            <form id="accountProfileForm" action="" method="post" enctype="multipart/form-data">
                                                <div class="row">
                                                    <div class="col-12">
                                                        <!-- Common message display area -->
                                                        <div id="formMessage" class="alert d-none"></div>
                                                    </div>
                                                </div>
                                                <div class="row mb-3">
                                                    <label for="profilePicture" class="col-md-4 col-lg-3 col-form-label">Profile Image</label>
                                                    <div class="col-md-8 col-lg-9">
                                                        <div class="d-flex">
                                                            <img id="profileImage" src="<?php echo BASE_URL . (!empty($profile_picture) ? htmlspecialchars($profile_picture) : 'assets/images/users/default.jpg'); ?>" class="flex-shrink-0 avatar-lg img-thumbnail" alt="Profile">
                                                            <div class="w-100 ps-3">
                                                                <div class="text-body-secondary font-monospace text-break small" id="fileName"></div>
                                                                <div class="text-body-secondary font-monospace small" id="fileSize"></div>
                                                                <div class="text-body-secondary font-monospace small" id="fileType"></div>
                                                            </div>
                                                        </div>
                                                        <div class="pt-2">
                                                            <div id="profileProgress" class="progress mb-2 d-none" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="height: 5px">
                                                                <div id="profileProgressStatus" class="progress-bar progress-bar-striped progress-bar-animated"></div>
                                                            </div>
                                                            <input class="d-none" type="file" name="profile_picture" id="profilePicture" onchange="fileSelected();" />
                                                            <label for="profilePicture" class="btn btn-primary btn-sm pb-0 px-1 me-2" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Upload Your Profile Picture" onclick="resetFileInput();">
                                                                <i class="dripicons-upload"></i>
                                                            </label>
                                                            <button id="deleteProfilePicture" class="btn btn-danger btn-sm pb-0 px-1" type="button" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Delete Current Profile Picture" title="Delete Current Profile Picture"><i class="dripicons-trash"></i></button>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="row mb-1">
                                                    <label for="fname" class="col-md-4 col-lg-3 col-form-label">First name</label>
                                                    <div class="col-md-8 col-lg-9">
                                                        <input class="form-control" type="text" id="fname" name="fname" value="<?php echo htmlspecialchars($f_name); ?>" placeholder="Enter your first name" autocomplete="off" required>
                                                    </div>
                                                </div>
                                                <div class="row mb-1">
                                                    <label for="lname" class="col-md-4 col-lg-3 col-form-label">Last name</label>
                                                    <div class="col-md-8 col-lg-9">
                                                        <input class="form-control" type="text" id="lname" name="lname" value="<?php echo htmlspecialchars($l_name); ?>" placeholder="Enter your last name" autocomplete="off" required>
                                                    </div>
                                                </div>
                                                <div class="row mb-3">
                                                    <label for="defaultEmail" class="col-md-4 col-lg-3 col-form-label">Main Email</label>
                                                    <div class="col-md-8 col-lg-9">
                                                        <input class="form-control" type="email" id="defaultEmail" name="defaultEmail" value="<?php echo htmlspecialchars($default_email); ?>" disabled readonly autocomplete="off" required>
                                                    </div>
                                                </div>
                                                <div class="row mb-3">
                                                    <label for="securityNotify" class="col-md-4 col-lg-3 col-form-label py-0">Email Notifications</label>
                                                    <div class="col-md-8 col-lg-9">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" name="notif_account_change" id="changesMade" <?php echo (($notif_account_change == 1) ? 'checked' : ''); ?>>
                                                            <label class="form-check-label" for="changesMade">
                                                                Changes made to your account
                                                            </label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" name="notif_news" id="newProducts" <?php echo (($notif_news == 1) ? 'checked' : ''); ?>>
                                                            <label class="form-check-label" for="newProducts">
                                                                Information on new products and services
                                                            </label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" name="notif_promo" id="proOffers" <?php echo (($notif_promo == 1) ? 'checked' : ''); ?>>
                                                            <label class="form-check-label" for="proOffers">
                                                                Marketing and promo offers
                                                            </label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" name="notif_security" id="securityNotify" <?php echo (($notif_security == 1) ? 'checked' : ''); ?>>
                                                            <label class="form-check-label" for="securityNotify">
                                                                Security alerts
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="text-center">
                                                    <button type="submit" class="btn btn-primary">
                                                        <span id="accountProfileSpinner" class="spinner-border spinner-border-sm me-1 d-none" role="status" aria-hidden="true" style="vertical-align: -0.25em;"></span>
                                                        Save Changes
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                        <div class="tab-pane show" id="additionalEmailTab">
                                            <p>
                                                Beatae, illo accusantium? Aut consectetur maiores voluptatum quae dicta eos iure nemo sapiente repellendus, recusandae excepturi enim doloremque cumque similique non, ex corporis deleniti natus? Consequatur sapiente vel laboriosam reprehenderit magnam hic mollitia, est eaque debitis tenetur nihil suscipit aliquam placeat aut doloremque deserunt sint ipsam cumque voluptate deleniti enim porro! Sapiente.
                                            </p>
                                            <p class="mb-0">
                                                Natus eos vitae recusandae quidem voluptates deleniti quos accusantium! Exercitationem laudantium magnam laboriosam velit. Eaque, quis cumque? Voluptates reiciendis deserunt velit alias molestias pariatur expedita odit accusantium? Quasi et rem voluptas accusamus.
                                            </p>
                                        </div>
                                        <div class="tab-pane" id="changePasswordTab">
                                            <form id="passwordUpdateForm" class="needs-validation" action="" method="POST" autocomplete="off" novalidate>
                                                <div class="row">
                                                    <div class="col-12">
                                                        <!-- Common message display area -->
                                                        <div id="passwordMessage" class="alert alert-warning d-none"></div>
                                                    </div>
                                                </div>
                                                <div class="row mb-1">
                                                    <label for="current_password" class="col-md-4 col-lg-3 col-form-label">Current Password</label>
                                                    <div class="col-md-8 col-lg-9">
                                                        <input name="current_password" type="password" class="form-control" id="current_password" placeholder="Enter your current password" autocomplete="off" required>
                                                    </div>
                                                </div>

                                                <div class="row mb-1">
                                                    <label for="new_password" class="col-md-4 col-lg-3 col-form-label">New Password</label>
                                                    <div class="col-md-8 col-lg-9">
                                                        <input name="new_password" type="password" class="form-control" id="new_password" placeholder="Enter your new password" autocomplete="off" required>
                                                    </div>
                                                </div>

                                                <div class="row">
                                                    <div class="col-md-8 col-lg-9 offset-md-4 offset-lg-3">
                                                        <div class="alert alert-warning d-none px-3 py-2 mt-0 mb-1" role="alert" id="password-alert">
                                                            <ul class="list-unstyled mb-0">
                                                                <li class="requirements leng">
                                                                    <i class="fas fa-check fa-fw text-success me-2"></i>
                                                                    <i class="fas fa-times fa-fw text-danger me-2"></i>
                                                                    Password must have at least 8 characters.
                                                                </li>
                                                                <li class="requirements big-letter">
                                                                    <i class="fas fa-check fa-fw text-success me-2"></i>
                                                                    <i class="fas fa-times fa-fw text-danger me-2"></i>
                                                                    Password must have at least 1 capital letter.
                                                                </li>
                                                                <li class="requirements num">
                                                                    <i class="fas fa-check fa-fw text-success me-2"></i>
                                                                    <i class="fas fa-times fa-fw text-danger me-2"></i>
                                                                    Password must have at least 1 number.
                                                                </li>
                                                                <li class="requirements special-char">
                                                                    <i class="fas fa-check fa-fw text-success me-2"></i>
                                                                    <i class="fas fa-times fa-fw text-danger me-2"></i>
                                                                    Password must have at least 1 special characters.
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="row mb-3">
                                                    <label for="confirm_password" class="col-md-4 col-lg-3 col-form-label">Re-enter New Password</label>
                                                    <div class="col-md-8 col-lg-9">
                                                        <input name="confirm_password" type="password" class="form-control" id="confirm_password" placeholder="Re-enter your new password" autocomplete="off" required>
                                                    </div>
                                                </div>

                                                <div class="text-center">
                                                    <button type="submit" class="btn btn-primary">
                                                        <span id="changePasswordSpinner" class="spinner-border spinner-border-sm me-1 d-none" role="status" aria-hidden="true" style="vertical-align: -0.25em;"></span>
                                                        Change Password
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>

And this is javascript for handling both the forms:
document.getElementById('accountProfileForm').addEventListener('submit', function(e) {
            e.preventDefault(); // Prevent default form submission

            // Display spinner
            document.getElementById("accountProfileSpinner").classList.remove("d-none");

            var form = e.target;
            var formData = new FormData(form);

            // Append the profile picture if a new one was selected
            if (profileImageBlob) {
                formData.append('profilePicture', profileImageBlob, 'profile_picture.png');
            }

            // Append the delete flag if the profile picture should be deleted
            if (deleteProfilePictureFlag) {
                formData.append('delete_profile_picture', '1');
            }

            // Send AJAX request to update-profile.php
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "<?php echo BASE_URL; ?>ajax/update-profile.php", true);

            xhr.onload = function() {
                // Show message div
                messageDiv.classList.remove('d-none');
                // Hide spinner
                document.getElementById("accountProfileSpinner").classList.add("d-none");

                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);

                    if (response.status === 'success') {
                        // Update the profile image src if returned
                        if (response.profile_picture) {
                            document.getElementById('profileImage').src = response.profile_picture;
                            document.getElementById('topBarProfileImage').src = response.profile_picture;
                            document.getElementById('profileImageLarge').src = response.profile_picture;
                        }

                        // Display success message
                        messageDiv.classList.remove('alert-danger');
                        messageDiv.classList.remove('alert-warning');
                        messageDiv.classList.add('alert-success');
                        messageDiv.innerHTML = response.message;
                        
                        // Optionally, reset the flags and variables
                        profileImageBlob = null;
                        deleteProfilePictureFlag = false;
                    } else {
                        // Display error message
                        messageDiv.classList.remove('alert-success');
                        messageDiv.classList.remove('alert-warning');
                        messageDiv.classList.add('alert-danger');
                        messageDiv.innerHTML = response.message;
                    }
                } else {
                    // Display error message for non-200 HTTP status
                    messageDiv.classList.remove('alert-success');
                    messageDiv.classList.remove('alert-warning');
                    messageDiv.classList.add('alert-danger');
                    messageDiv.innerHTML = 'An error occurred while updating your profile. Please try again later.';
                }
            };
            
            xhr.onerror = function() {
                // Handle network errors
                messageDiv.classList.remove('d-none');
                messageDiv.classList.remove('alert-success');
                messageDiv.classList.remove('alert-warning');
                messageDiv.classList.add('alert-danger');
                messageDiv.innerHTML = 'A network error occurred. Please check your internet connection and try again.';
                // Hide spinner
                document.getElementById("accountProfileSpinner").classList.add("d-none");
            };

            xhr.send(formData);
        });

document.getElementById('passwordUpdateForm').addEventListener('submit', function(e) {
            e.preventDefault(); // Prevent default form submission

            // Display spinner if you have one
            document.getElementById("changePasswordSpinner").classList.remove("d-none");

            var form = e.target;
            var formData = new FormData(form);

            // Send AJAX request to change-password.php
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "<?php echo BASE_URL; ?>ajax/change-password.php", true);

            xhr.onload = function() {
                // Hide spinner as request has completed
                document.getElementById("changePasswordSpinner").classList.add("d-none");

                var passwordmessageDiv = document.getElementById('passwordMessage');

                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);

                    if (response.status === 'success') {
                        // Display success message
                        passwordmessageDiv.classList.remove('alert-danger', 'alert-warning', 'd-none');
                        passwordmessageDiv.classList.add('alert-success');
                        passwordmessageDiv.innerHTML = response.message;

                        // Optionally, reset the form
                        form.reset();
                    } else {
                        // Display error message
                        passwordmessageDiv.classList.remove('alert-success', 'alert-warning', 'd-none');
                        passwordmessageDiv.classList.add('alert-danger');
                        passwordmessageDiv.innerHTML = response.message;
                    }
                } else {
                    // Display error message for non-200 HTTP status
                    passwordmessageDiv.classList.remove('alert-success', 'alert-warning', 'd-none');
                    passwordmessageDiv.classList.add('alert-danger');
                    passwordmessageDiv.innerHTML = 'An error occurred while changing your password. Please try again later.';
                }
            };

            xhr.onerror = function() {
                // Hide spinner as request has completed with an error
                document.getElementById("changePasswordSpinner").classList.add("d-none");

                var passwordmessageDiv = document.getElementById('password-alert');

                // Handle network errors
                passwordmessageDiv.classList.remove('alert-success', 'alert-warning', 'd-none');
                passwordmessageDiv.classList.add('alert-danger');
                passwordmessageDiv.innerHTML = 'A network error occurred. Please check your internet connection and try again.';
            };

            xhr.send(formData);
        });

And this is change-password.php:
<?php
    // Include necessary files
    include '../includes/config.php';
    include '../includes/commonVariables.php';
    include '../includes/commonFunctions.php';
    include '../includes/auth.php';
    require '../vendor/autoload.php';

    // Check if the user is logged in
    if (!isset($_SESSION['uid'])) {
        echo json_encode(array(
            'status' => 'error', 
            'message' => 'You must be logged in to change your password.'
        ));
        exit;
    }

    // Initialize the response array
    $response = array('status' => 'error', 'message' => '');

    $user_id = $_SESSION['uid'];

    // Sanitize and validate inputs
    $current_password = isset($_POST['current_password']) ? trim($_POST['current_password']) : '';
    $new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
    $confirm_password = isset($_POST['confirm_password']) ? trim($_POST['confirm_password']) : '';

    // Check if inputs are empty
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $response['message'] = 'All fields are required.';
        echo json_encode($response);
        exit;
    }

    // Validate new password strength
    $errors = array();

    if (strlen($new_password) < 8) {
        $errors[] = 'Password must have at least 8 characters.';
    }
    if (!preg_match('/[A-Z]/', $new_password)) {
        $errors[] = 'Password must contain at least one uppercase letter.';
    }
    if (!preg_match('/[a-z]/', $new_password)) {
        $errors[] = 'Password must contain at least one lowercase letter.';
    }
    if (!preg_match('/[0-9]/', $new_password)) {
        $errors[] = 'Password must contain at least one number.';
    }
    if (!preg_match('/[\W]/', $new_password)) {
        $errors[] = 'Password must contain at least one special character.';
    }

    // Check if new password and confirm password match
    if ($new_password !== $confirm_password) {
        $errors[] = 'New password and confirm password do not match.';
    }

    // Return errors if any
    if (!empty($errors)) {
        $response['message'] = implode(' ', $errors);
        echo json_encode($response);
        exit;
    }

    // Fetch the current password hash from the database
    $sql = "SELECT `password` FROM `users` WHERE `uid` = ?";
    $stmt = mysqli_prepare($conn, $sql);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 's', $user_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $hashed_password);
        mysqli_stmt_fetch($stmt);
        mysqli_stmt_close($stmt);
    } else {
        $response['message'] = 'Failed to retrieve user information.';
        echo json_encode($response);
        exit;
    }

    // Verify the current password
    if (!password_verify($current_password, $hashed_password)) {
        $response['message'] = 'Current password is incorrect.';
        echo json_encode($response);
        exit;
    }

    // Hash the new password
    $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);

    // Update the password in the database
    $update_sql = "UPDATE `users` SET `password` = ? WHERE `uid` = ?";
    $update_stmt = mysqli_prepare($conn, $update_sql);
    if ($update_stmt) {
        mysqli_stmt_bind_param($update_stmt, 'ss', $new_password_hash, $user_id);
        if (mysqli_stmt_execute($update_stmt)) {
            // Password updated successfully
            $response['status'] = 'success';
            $response['message'] = 'Your password has been successfully updated.';
        } else {
            $response['message'] = 'Failed to update password. Please try again.';
            echo json_encode($response);
            exit;
        }
        mysqli_stmt_close($update_stmt);
    } else {
        $response['message'] = 'Failed to prepare the password update statement.';
        echo json_encode($response);
        exit;
    }

    // Optionally, send a notification email if the user has opted in

    // Retrieve user's email, name, and notification preference
    $query = "SELECT  up.`notification_pref_security`, u.`email`, u.`first_name`, u.`last_name` FROM `user_profile` up INNER JOIN `users` u ON up.`uid` = u.`uid` WHERE up.`uid` = ?";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 's', $user_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $notification_pref_security, $email, $first_name, $last_name);
        mysqli_stmt_fetch($stmt);
        mysqli_stmt_close($stmt);
    } else {
        // If fetching user info fails, continue without sending email
        $notification_pref_security = 0;
    }

    // If user has opted in for notifications, send an email
    if ($notification_pref_security == 1) {
        $fullName = $first_name . ' ' . $last_name;
        $emailBody = file_get_contents('../templates/passwordChangeEmailTemplate.html');
        $toReplace = ['::BASEURL::', '::FULLNAME::', '::CURRENTYEAR::'];
        $withThis = [BASE_URL, $fullName, date('Y')];
        $emailBody = str_replace($toReplace, $withThis, $emailBody);

        // Prepare email variables
        $toEmail = $email; // Recipient's email address
        $toName = $fullName; // Recipient's full name
        $subject = 'Notification: Your TrackBack.email Password Has Been Changed';
        $body = $emailBody; // Your HTML email body

        // Send the email
        sendEmailNoReply($toEmail, $toName, $subject, $body);
    }

    // Return the JSON response
    echo json_encode($response);

    // Close the database connection
    mysqli_close($conn);
?>

And this is update-profile.php:
<?php
    include '../includes/config.php';
    include '../includes/commonVariables.php';
    include '../includes/commonFunctions.php';
    include '../includes/auth.php';
    require '../vendor/autoload.php';

    // Check if the user is logged in
    if (!isset($_SESSION['uid'])) {
        echo json_encode(array(
            'status' => 'error', 
            'message' => 'You must be logged in to update your profile.'
        ));
        exit;
    }

    $user_id = $_SESSION['uid'];
    $response = array('status' => 'error', 'message' => '');

    // Get the current profile picture file path from the database
    // Prepare the query to select data from both tables using a JOIN
    $queryUserInfo = "SELECT up.`notification_pref_account_change`, u.`email`, u.`first_name`, u.`last_name` FROM `user_profile` up INNER JOIN `users` u ON up.`uid` = u.`uid` WHERE up.`uid` = ?";
    $stmtUserInfo = mysqli_prepare($conn, $queryUserInfo);
    // Bind the user ID parameter
    mysqli_stmt_bind_param($stmtUserInfo, 's', $user_id);
    // Execute the statement
    mysqli_stmt_execute($stmtUserInfo);
    // Bind the result variables
    mysqli_stmt_bind_result($stmtUserInfo, $notification_pref_account_change, $email, $first_name, $last_name);
    mysqli_stmt_fetch($stmtUserInfo);
    mysqli_stmt_close($stmtUserInfo);

    $fullName = $first_name . ' ' . $last_name;

    // Sanitize and validate inputs
    $fname = trim($_POST['fname']);
    $lname = trim($_POST['lname']);
    $notif_account_change = isset($_POST['notif_account_change']) ? 1 : 0;
    $notif_news = isset($_POST['notif_news']) ? 1 : 0;
    $notif_promo = isset($_POST['notif_promo']) ? 1 : 0;
    $notif_security = isset($_POST['notif_security']) ? 1 : 0;

    // Update 'users' table
    $updateUserQuery = "UPDATE `users` SET `first_name` = ?, `last_name` = ? WHERE `uid` = ?";
    $stmt = mysqli_prepare($conn, $updateUserQuery);
    mysqli_stmt_bind_param($stmt, 'ssi', $fname, $lname, $user_id);
    if (!mysqli_stmt_execute($stmt)) {
        $response['message'] = 'Failed to update user information.';
        echo json_encode($response);
        exit;
    }
    mysqli_stmt_close($stmt);

    // Update 'user_profile' table
    $updateProfileQuery = "UPDATE `user_profile` SET `notification_pref_account_change` = ?, `notification_pref_news` = ?, `notification_pref_promo` = ?, `notification_pref_security` = ? WHERE `uid` = ?";
    $stmt = mysqli_prepare($conn, $updateProfileQuery);
    mysqli_stmt_bind_param($stmt, 'iiiis', $notif_account_change, $notif_news, $notif_promo, $notif_security, $user_id);
    if (!mysqli_stmt_execute($stmt)) {
        $response['message'] = 'Failed to update user profile.';
        echo json_encode($response);
        exit;
    }
    mysqli_stmt_close($stmt);

    // Handle profile picture deletion
    if (isset($_POST['delete_profile_picture']) && $_POST['delete_profile_picture'] == '1') {
        // Get the current profile picture file path from the database
        $query = "SELECT `profile_picture` FROM `user_profile` WHERE `uid` = ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, 's', $user_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $profile_picture);
        mysqli_stmt_fetch($stmt);
        mysqli_stmt_close($stmt);

        if ($profile_picture && file_exists('../' . $profile_picture)) {
            // Delete the file
            unlink('../' . $profile_picture);
        }

        // Update the database
        $updateQuery = "UPDATE `user_profile` SET `profile_picture` = '' WHERE `uid` = ?";
        $stmt = mysqli_prepare($conn, $updateQuery);
        mysqli_stmt_bind_param($stmt, 's', $user_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);

        $response['profile_picture'] = 'assets/images/users/default.jpg';
    }

    // Handle profile picture upload
    if (isset($_FILES['profilePicture']) && $_FILES['profilePicture']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['profilePicture'];

        // Get file info
        $filename = $file['name'];
        $fileTmpName = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileType = $file['type'];

        // Allowed file extensions and MIME types
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
        $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'];

        // Get the file extension
        $fileExt = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        // Validate file extension and MIME type
        if (in_array($fileExt, $allowedExtensions) && in_array($fileType, $allowedMimeTypes)) {
            // Check file size (limit to 5MB)
            $maxFileSize = 5 * 1024 * 1024; // 5MB

            if ($fileSize <= $maxFileSize) {
                // Define the target directory
                $target_dir = '../assets/images/users/'; // Adjust the path as needed

                // Ensure the directory exists
                if (!is_dir($target_dir)) {
                    mkdir($target_dir, 0755, true);
                }

                // Generate new filename
                $newFilename = 'user' . $user_id . '_profile_' . time() . '.' . $fileExt;

                // Target file path
                $target_file = $target_dir . $newFilename;

                // Move uploaded file to target directory
                if (move_uploaded_file($fileTmpName, $target_file)) {
                    $profile_picture_url = 'assets/images/users/' . $newFilename; // Adjust if needed

                    // Update the database
                    $updateQuery = "UPDATE `user_profile` SET `profile_picture` = ? WHERE `uid` = ?";
                    $stmt = mysqli_prepare($conn, $updateQuery);
                    mysqli_stmt_bind_param($stmt, 'ss', $profile_picture_url, $user_id);
                    if (mysqli_stmt_execute($stmt)) {
                        $response['profile_picture'] = $profile_picture_url;
                    } else {
                        $response['message'] = 'Failed to update profile picture in database.';
                        echo json_encode($response);
                        exit;
                    }
                    mysqli_stmt_close($stmt);
                } else {
                    $response['message'] = 'Failed to move the uploaded file.';
                    echo json_encode($response);
                    exit;
                }
            } else {
                $response['message'] = 'File size exceeds the limit of 5MB.';
                echo json_encode($response);
                exit;
            }
        } else {
            $response['message'] = 'Invalid file type. Only JPG, JPEG, PNG, GIF, BMP files are allowed.';
            echo json_encode($response);
            exit;
        }
    } elseif (isset($_FILES['profilePicture']) && $_FILES['profilePicture']['error'] !== UPLOAD_ERR_NO_FILE) {
        // Handle upload errors
        $uploadError = $_FILES['profilePicture']['error'];
        $errorMessage = '';

        switch ($uploadError) {
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                $errorMessage = 'File size exceeds the allowed limit.';
                break;
            case UPLOAD_ERR_PARTIAL:
                $errorMessage = 'File upload was not completed.';
                break;
            default:
                $errorMessage = 'An error occurred during file upload.';
                break;
        }
        $response['message'] = $errorMessage;
        echo json_encode($response);
        exit;
    }

    // If everything was successful
    $response['status'] = 'success';
    $response['message'] = 'Profile updated successfully.';

    if ($notification_pref_account_change && $notification_pref_account_change === 1) {
        // Process to send account change notification email
        $emailBody = file_get_contents('../templates/accountChangeEmailTemplate.html');
        $toReplace = ['::BASEURL::', '::FULLNAME::', '::CURRENTYEAR::'];
        $withThis = [BASE_URL, $fullName, $currentYear];
        $emailBody = str_replace($toReplace, $withThis, $emailBody);

        // Prepare email variables
        $toEmail = $email; // Recipient's email address
        $toName = $fullName; // Recipient's full name
        $subject = 'Notification: Changes Made to Your TrackBack.email Account';
        $body = $emailBody; // Your HTML email body

        // Send the email
        sendEmailNoReply($toEmail, $toName, $subject, $body);
    }

    echo json_encode($response);
?>

Now, I want to add CSRF protection for this.
I already have implemented it on page form submission like this:
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

<?php
// CSRF token generation and session check
    if (!isset($_SESSION["csrf_token"]) || empty($_SESSION['csrf_token'])) {
        $csrf_token = generateRandomString(32);
        $_SESSION["csrf_token"] = $csrf_token;
    } else {
        $csrf_token = $_SESSION['csrf_token'];
    }

if (!isset($_POST['csrf_token']) || empty($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            $errorMSG = "Invalid CSRF token. Please try again.";
        }
?>

I want you to add CSRF protection in these AJAX forms.