wp_ajax action is not running

I’m writing a plugin.
I want to run the method get_my_option when someone pressing a button in the settings page of my wordpress plugin. The ajax call is made but the method never runs.

In the page I have the following code:

<div class="wrap">
<input type="button" value="test" onclick="my_js_function();"/>
</div>
<?php
wp_enqueue_script( 'function', plugins_url( '/js/synchandler.js',__FILE__),         array('jquery'));
wp_localize_script( 'function', 'my_ajax_script', array( 'ajaxurl' => admin_url(  'admin-ajax.php' ) ) );


function get_my_option()
{
    //do something
    die();
}

add_action("wp_ajax_nopriv_get_my_option", "get_my_option");
add_action("wp_ajax_get_my_option", "get_my_option");
?>

The added synchandler.js file:

function my_js_function() 
{
    jQuery.ajax({
    url: my_ajax_script.ajaxurl,
    type: 'POST',
    data: ({ action: 'get_my_option', affiliate: 'daisycon' }),
    success: function (response) {
        console.log("got this: " + response);
        }
    });
}

There is a response but that’s a 0, so the javascript is added nicely but that’s about it. I’m getting no errors in my log by running this. AjaxURL is added in the page (seems to be a common mistake).

/* <![CDATA[ */
var my_ajax_script = {"ajaxurl":"http:\/\/mywebsite.net\/wp-admin\/admin-ajax.php"};
/* ]]> */

The button to trigger it all uses onclick="my_js_function(); on the HTML button-tag.

As easy as it is, the method get_my_option doesn’t get triggered by the ajax call. What am I doing wrong here?

Solutions Collecting From Web of "wp_ajax action is not running"

Where are you calling add_action()? If it’s in a place where you’re already outputting HTML, it’s too late, and that’s probably a place that wont even be looked at during an AJAX request.

You should include that code in your theme’s functions.php file, or as early as possible in a plugin.

You’ll need to put your functional code into the plugin, as a function (This depending on your way of developing your plugin.

I prefer to add the add_action calls to admin_init – It’s called with admin-ajax.php too.

wp_enqueue_script( 'function', plugins_url( '/js/synchandler.js',__FILE__),         array('jquery'));
wp_localize_script( 'function', 'my_ajax_script', array( 'ajaxurl' => admin_url(  'admin-ajax.php' ) ) );


function get_my_option()
{
    //do something
    die();
}
function add_ajax_actions() {
    add_action("wp_ajax_nopriv_get_my_option", "get_my_option");
    add_action("wp_ajax_get_my_option", "get_my_option");
}
add_action( 'admin_init', 'add_ajax_actions' );

I don’t know if this is best practice – It’s purely a personal preference, to avoid adding hooks to every page loaded – Only to admin pages.