Plugin onclick button activate other plugin

So I did a couple of things. First I added an ID to the HTML button just to make life a bit easier in case there end up being multiple buttons with the same classes doing different things.

Then I wrote a quick and simple little AJAX function – doesn’t really need to pass much data, it just needs to verify itself to WP so that WP knows it’s allowed to execute the function.

Then I wrote another function in php that basically activates the plugin.

<!-- //ADDED AN ID TO THE BUTTON -->
<button id="activate_plugin" class="btn btn-success">Activate</button>

<!-- //THE AJAX -->
<script type="text/javascript">
jQuery( document ).ready( function($) {
    $( '#activate_plugin' ).on( 'click', function(e) {
        e.preventDefault();
        var ajaxurl="<?php echo admin_url( "admin-ajax.php" ); ?>";
        var security    = '<?php echo wp_create_nonce( "activate_plugin" ); ?>';
        $.ajax( {
            url: ajaxurl,
            dataType: 'json',
            type: 'POST',
            delay: 150,
            data :'action=activate_plugin&security='+security,
            success: function( data ) {
                console.log( data + ', Plugin Activated!' );
            },
        } );
    } );
} );
</script>

<!-- //THE AJAX CALLBACK -->
<?php
    function activate_plugin_ajax_callback() {
        check_ajax_referer( 'activate_plugin', 'security' );
        activate_plugin( 'plugin-dir/plugin-file.php' );
        if( is_wp_error( $result ) ) {
            // Process Error
        }
    }
    add_action( 'wp_ajax_activate_plugin', 'activate_plugin_ajax_callback' );
    add_action( 'wp_ajax_nopriv_activate_plugin', 'activate_plugin_ajax_callback' );
?>

There’s a lot of other neat little things you can do, like IF the plugin is already active, then don’t even display the button.

<?php if( is_plugin_inactive( 'plugin-dir/plugin-file.php' ) ) : ?>
<button id="activate_plugin" class="btn btn-success" onclick="testme()">Activate</button>
<?php else : ?>
<span class="activated-note">The XXX Plugin is installed and activated.</span>
<?php endif; ?>

You could also set your AJAX success to remove the button and add the note by replacing the success portion of your AJAX with:

success: function( data ) {
    console.log( data );
    alert( 'Plugin Activated!' );
    $( '#activate_plugin' ).toggle();
    $( '.navbar-header' ).append( '<span class="activated-note">The XXX Plugin is installed and activated.</span>' );
},