I’m trying to make use of WP_Ajax
but having problems while testing and I think it could be related to the functions Namespace. Pointers are really appreciated. Maybe is just that I’m lost…
The $.ajax
call is returning 0
.
What I don’t know is if the function is actually being called.
If that was the case, how would I call the function for its namespace on js
within data : {action: 'action_name'}
?
Ajax call:
$.ajax({
url : wpadmin.adminAjax,
data : {
action: 'action_name'
},
success: function(response) {
console.log(response);
}
});
Function:
add_action( 'wp_ajax_action_name', __NAMESPACE__ . '\\action_name' );
add_action( 'wp_ajax_nopriv_action_name', __NAMESPACE__ . '\\action_name' );
function action_name() {
return 'stuff';
die();
}
Nothing to do with Namespaces, the function it’s being called but it should echo
instead of return
for the purpose of this test.
add_action( 'wp_ajax_action_name', __NAMESPACE__ . '\\action_name_callback' );
add_action( 'wp_ajax_nopriv_action_name', __NAMESPACE__ . '\\action_name_callback' );
function action_name_callback() {
echo 'stuff';
die();
}
1 Like
Foxaii
February 13, 2016, 11:57am
3
Thanks for following up with your own solution. It makes maintaining the forum so much easier.
xav
May 7, 2017, 9:14pm
4
you have to call admin-ajax.php but which path did you use?
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/assets/scripts/main.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', __NAMESPACE__ .'\\my_enqueue' );
xav
May 7, 2017, 10:28pm
6
I find the way to do it, you have to open Ajax in setup.php
function my_enqueue() {
wp_enqueue_script('sage/js', Assets\asset_path('scripts/main.js'), ['jquery'], null, true);
wp_localize_script( 'sage/js', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', __NAMESPACE__ .'\\my_enqueue' );
1 Like