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?

2 Answers
2

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.

Leave a Reply

Your email address will not be published. Required fields are marked *