Here I am facing a problem with the admin-ajax.php of wordpress.
Indeed my project is particular since it contains 2 parts (customer part and admin part). The first part is for the client part since (/wp-content/themes/my_theme_child) is standard.
I have another folder for the admin (/manager/eliteadmin/) and there, impossible to use the standard methods to activate the admin-ajax as I usually do in the functions.php of the child, i.e. something like this for example:
function wpchild_enqueue_styles(){
wp_enqueue_script('global', get_stylesheet_directory_uri().'/ajax/global.js', array('jquery'), "", true);
wp_enqueue_script('services', get_stylesheet_directory_uri().'/ajax/services.js', array('jquery'), "", true);
wp_localize_script('services', 'ajaxurl', admin_url('admin-ajax.php'));
}
here is the structure :
In the part of the manager I try to use ajax, for example:
add_action('wp_ajax_get_citoyens', 'get_citoyens_ajax');
add_action('wp_ajax_nopriv_get_citoyens', 'get_citoyens_ajax');
function get_citoyens_ajax(){
$context = array();
$context['response'] = 'ok';
echo json_encode($context);
wp_die();
}
js file :
function display(){
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {
action: 'get_citoyens'
},
success: function(context) {
var data = JSON.parse(context);
if(data.response === 'ok') {
console.log("it works");
}
},
error: function(json) {
console.log('error');
}
});
}
php file :
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
So obviously in the manager part I can’t use the wp_enqueue_script and wp_localize_script. So my question is the next: how to properly use admin-ajax in this particular context, thank you very much!
2
Answers
Have you tried to return data with wp_send_json()?
ref https://developer.wordpress.org/reference/functions/wp_send_json/
You need to paste the
exit();
at the end of function ajax.