I see a couple things wrong here. If you are using ajax with WordPress you should be running it through the admin ajax url.
You aren't using do_action
properly. The first parameter is the name of the action and the second should be the arguments for the action. I think you are confusing do_action
with add_action
.
It's best practice to use die()
or better yet wp_die()
when you finish your ajax handler. Alternatively if you are returning some output you can use wp_send_json()
Your ajaxurl
should always point to the admin-ajax.php. If you are doing this on the admin side ajaxurl
is already setup for you. If you are doing this on the frontend you should have a snippet like the following in your functions.php
add_action( 'wp_enqueue_scripts', 'my_scripts' );
function my_scripts() {
// the file where your javascript is located
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/script.js', array('jquery') );
// this makes the admin url available to your javascript
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
You can then use ajax_object.ajaxurl
in your javascript to get the right URL.
Your javascript may now look something like this:
$('#clear_cache').click(function (event) {
event.preventDefault();
var data = { action: 'clear_transients' }
$.post( ajax_object.ajaxurl, data, function () {
$('<p>The cache was cleared successfully.</p>').insertAfter('#clear_cache');
});
});
If you are running this in the admin just replace ajax_object.ajaxurl
with ajaxurl
. Notice the addition of the data
variable. This will tell WordPress which action it should be running.
For your actions you should be using the wp_ajax_(action)
for admin side or the wp_ajax_nopriv_(action)
for the frontend.
This would change your ajax handler function to something like this:
// run on the admin side
add_action( 'wp_ajax_clear_transients', 'clear_transients' );
// or run on the frontend
add_action( 'wp_ajax_nopriv_clear_transients', 'clear_transients' );
function clear_transients() {
global $wpdb;
$sql = "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_cc%'";
$wpdb->query($sql);
wp_die();
}
Your ajax handler can also be placed in the functions.php.
One thing I did not mention is nonces. You should be using nonces for security. Nonces are used with check_ajax_referer to make sure ajax requests are originating from the correct source.