$wpdb not working wordpress plugin ajax call

The reason your wpdb call fails is because there is no wpdb. You’ve taken the incorrect route of using a standalone PHP file, so there is no WordPress API. WordPress never gets loaded. That’s not how you do AJAX in WordPress.

The solution is to do the AJAX call correctly and register a REST API endpoint.

E.g. in a plugin or a themes functions.php, register an endpoint:

add_action( 'rest_api_init', function () {
        register_rest_route( 'harriecrm/v1', '/contacts/', array(
                'methods' => 'GET',
                'callback' => 'get_contacts'
        ) );
} );

function get_contacts( $request ) {
    $id = $request['organisation_id'];
    .... your code goes here
    return "result";
}

Then make your AJAX request to yoursite.com/wp-json/harriecrm/v1/contacts and change it from a POST to a GET:

            $.ajax({
                type: 'GET',
                url:  '/wp-json/harriecrm/v1/contacts',

This gives you several advantages:

  1. You can expand the register_rest_route call to tell WP to expect an organisation ID, what format it takes, and it will do all the validating and sanitising for you!
  2. The endpoint goes away when you deactive the plugin, and it only appears on sites that have the plugin activated, closing a major security hole in your plugin
  3. You can put your code anywhere in your plugins codebase now
  4. The WordPress API, including wpdb is now loaded when your code runs
  5. The API is self documenting
  6. If you need to modify or add, you can register POST DELETE and other routes
  7. You can make register_rest_route handle authentication for you
  8. You can use tools such as Postman with this system
  9. If you redo your plugin you can do harriecrm/v2 so that things don’t break for old code

And there are many other advantages. Using a standalone PHP file that you make direct requests to is extremely bad practice, and your question highlights one of the major issues.