Using jQuery to delete data stored in wp_options

Ajax in WordPress works by sending an HTTP post to /wp-admin/admin-ajax.php (by default) that then fires the corresponding hook. So, you attach some jquery to an event triggered by your delete button, which then posts to admin-ajax.php, which has an action, say, delete_my_options(), which actually runs the php to delete. Then, you have a function, called a callback, that runs on successful completion of the ajax request. You could use this to fade your #log div out for example.

In short, you have three steps, the action, the ajax and the callback. The action is triggered by a DOM event and attached to two hooks, wp_ajax_{action_name} and wp_ajax_nopriv_{action_name} (only if you want no logged in users to be able to do it). These fire when that action is posted to wp-admin/admin-ajax.php. The ajax is the php (usually) function hooked to them. The callback function is a javascript function that is fired when the ajax is successfully completed.

Step by step:

Step 1, in your js file

jQuery('#hide_debug').click(function()
{
    var data = {};
    data.action = 'clear_log_action';
    data.options_delete_nonce = ajax_object.options_delete_nonce;
    jQuery.post(ajax_object.ajax_url, data, clear_log_callback);

}); 

Step 2, in your functions.php or a plugin

Add this to the function that you enqueue your javascript from: (thanks @Milo)

wp_localize_script( 'my_js_file_name', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ,   'options_delete_nonce' => wp_create_nonce( 'options_delete_nonce' ), ) );

Then add this to your functions.php or plugin:

// Edit: removed the nopriv hook (Thanks @toscho)
add_action('wp_ajax_clear_log_action','clear_log_ajax'); // attach your data.action to wp_ajax and wp_ajax_nopriv and hook your php function
function clear_log_ajax() {
    $nonce = $_POST['options_delete_nonce'];
    // Edit: Added nonces and permissions check (Thanks @Otto)
    if( wp_verify_nonce( $nonce, 'options_delete_nonce' ) && current_user_can( 'manage_options' ) ) {
        delete_option('wow_tweets_log');
        die(); // make sure to put a die() or exit() at the end of your ajax
    }
}

Step 3, back in your js file

// output will be what is echoed from your ajax, if anything
function clear_log_callback(output) 
{
    jQuery('#log').hide();
}

Leave a Comment