Frontend AJAX Request causes Error: ‘Call to undefined function add_action’

I wrote a little plugin that is supposed to handle a form submission and send some mails. When the form is submitted the request fails.

Im on a local MAMP Environment and my PHP error log shows me this error which is triggered in the main.php.

I couldn’t find a way to fix this, why is add_action not available in this context? Do I need to place the add_action calls elsewhere?

error

Uncaught Error: Call to undefined function add_action()

plugin/main.php

function my_enqueue() {
wp_enqueue_script( ‘ajax-script’, plugins_url( ‘/script.js’, __FILE__ ), array(‘jquery’) );
wp_localize_script( ‘ajax-script’, ‘the_ajax_script’, array( ‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ) ) );
}
add_action( ‘wp_enqueue_scripts’, ‘my_enqueue’ ); // this line causes the error

function send_emails() {
// do stuff
}
add_action( ‘wp_ajax_send_mails’, ‘send_mails’ );
add_action( ‘wp_ajax_nopriv_send_mails’, ‘send_mails’ ); // trigger for not logged in users as well

plugin/script.js

$.ajax({
url: the_ajax_script.ajaxurl,
type: ‘POST’,
data: {
action: ‘send_mails’
},
success: function (response) {
console.log(“success”);
},
error: function (error) {
console.log(“error”);
e.preventDefault();
return false
}
});

Read more here:: Frontend AJAX Request causes Error: ‘Call to undefined function add_action’

Leave a Reply

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