I'm trying to make a custom plugin, and something that should be simple is giving me a huge headache. I followed the Wordpress Codex example exactly and have looked at countless similar posts but nothing has worked for me.
Here is the structure of my code:
In my_plugin.php file, which contains my main plugin class and all my php functions I have (inside my main class):
public function __construct() {
add_action( 'wp_ajax_foobar', array( $this,
'my_ajax_foobar_handler') );
add_action( 'wp_ajax_nopriv_foobar', array( $this,
'my_ajax_foobar_handler' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'my_enqueue') );
}
public function my_enqueue() {
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js',
__FILE__ ), array('jquery') );
wp_localize_script( 'ajax-script', 'my_foobar_client', array(
'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
public function my_ajax_foobar_handler() {
error_log("Ajax callback");
// Don't forget to stop execution afterward.
wp_die();
}
In another page, my_page.php I have:
<input type="submit" class="button" name="insert" value="Submit" />
<script>
// Create a function to pick up the link click
$('button').click(function(){
<?php error_log("Got button click"); ?>
jQuery.post(
my_foobar_client.ajaxurl,
{
'action': 'foobar',
'foobar_id': 123
}
);
</script>
When I click the button, my log file picks up the "Got button click" fine, so the button click is being detected on the front end. However, my debug log does not pickup the "Ajax callback". I don't understand why this is not working.
Any help would be appreciated. Thanks.
my_foobar_client.ajaxurl
?