PHP includes with AJAX actions

I have the following code in my main plugin file

?php
include plugin_dir_path( __FILE__) . 'options.php';
include plugin_dir_path( __FILE__ ) . 'config.php';
include plugin_dir_path( __FILE__ ) . 'front/manage.php';
add_action( 'admin_init', 'restrict_admin', 1 );

//prepare wordpress for ajax  this needs to be done early to avoid strange race conditions
add_action( 'wp_ajax_devices', 'api_list_devices' );
add_action( 'wp_ajax_profiles', 'api_list_profiles' );
add_action( 'wp_ajax_held_accounts', 'api_list_held_accounts' );
add_action( 'wp_ajax_set_profile', 'api_set_profiles' );

define('AJAX_NONCE_NAME',"title_example");
//...

I assume since adding an action just lets admin-ajax.php know it should run some action at some point later, my includes aren't even executed, but I need them to authenticate the database connection. How can I tell wordpress to do my includes for parts of wordpress like this that are beyond my control? Do I have to enqueue, all the enqueueing examples seem to apply to the front end?

Topic wp-dependencies ajax plugin-development customization Wordpress

Category Web


I wound up doing the following:

  1. prepending a function to each of my ajax actions that loads a file full of defines
  2. left my database connection functions in the main plugin files since php includes are scoped to the function in which they occurred(but define values are global)

If anyone reading this happens to need an object, do step one but use the global keyword to assign the loaded object to the global namespace so it isn't lost when your dependency loading function is done, then simply refer to the global instance of your object.

If a wordpress dev happens to be reading this, there should be a hook for loading dependencies before ajax happens, you can use reflection to make this transparent.

  1. Instruct plugin developer to check referer nonce to guard against malicious plugins.
  2. Use reflection to load handlers scope into caller scope see: https://stackoverflow.com/questions/2211877/giving-php-included-files-parent-variable-scope

  3. Call ajax action handler as usual.


"...I need them to authenticate the database connection."

Not exactly sure this is what you want, but in your ajax function you can connect to and use a database if you declare the global variable $wpdb.

Here's a simple example:

function api_list_devices() {
    global $wpdb;

    $name = $_POST['name']; // ajax call sends "name"

    // try to insert $name into "people" tables "name" column
    if($wpdb->insert('people',array(
        'name'=>$name 
    ))===FALSE){
        echo "Error";
    }
    else {
        echo "Person '".$name. "' has been successfully added;
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.