$wpdb selects wrong database

$_SERVER['DOCUMENT_ROOT']; is not going to include secondsite. So all the files, including wp-config.php with the database details, are coming from the root public directory.

To get the current directory, including subdirectories, use any of these:

getcwd();

dirname(__FILE__);

basename(__DIR__);

But if your file is in a deeper folder, you can’t find the secondsite directory without specifying it (or scanning directories to find a WordPress installation). So you need to manually specify it like so:

$path = $_SERVER['DOCUMENT_ROOT'] . '/secondsite';

But your problem is that you’re doing AJAX wrong. You shouldn’t be sending AJAX requests directly to a file in your plugin. You should be using the AJAX hooks or adding a custom endpoint to the REST API.