I’m trying to implement an autocomplete feature in my WordPress admin area using Select2 and AJAX. However, I’m having trouble getting the AJAX requests to work correctly.
PHP Code to Handle the AJAX Request:
function get_tags_suggestions() {
if (!current_user_can('edit_posts')) {
error_log('get_tags_suggestions: Unauthorized'); // Debug log
wp_send_json_error('Unauthorized', 403);
}
$search_term = sanitize_text_field($_GET['term']);
error_log('get_tags_suggestions: Search term - ' . $search_term); // Debug log
$tags = get_tags(array(
'search' => $search_term,
'hide_empty' => false,
));
error_log('get_tags_suggestions: Tags found - ' . print_r($tags, true)); // Debug log
$suggestions = array();
foreach ($tags as $tag) {
$suggestions[] = array(
'id' => $tag->slug,
'text' => $tag->name,
);
}
wp_send_json_success($suggestions);
}
add_action('wp_ajax_get_tags_suggestions', 'get_tags_suggestions');
JavaScript Code for AJAX Request:
jQuery(document).ready(function($) {
console.log('Custom admin JS is loaded');
function setupAutocomplete(field, ajaxAction) {
console.log('Setting up autocomplete for action: ' + ajaxAction);
field.select2({
ajax: {
url: ajaxurl, // Use localized ajaxurl
type: "POST", // Changed from GET to POST
dataType: 'json',
delay: 250,
data: function(params) {
console.log('Sending AJAX request for action: ' + ajaxAction + ' with term: ' + params.term);
return {
action: ajaxAction,
term: params.term || '',
page: params.page || 1,
security: my_ajax_object.nonce // Added nonce for security
};
},
processResults: function(response, params) {
params.page = params.page || 1;
console.log('Received response: ', response);
// Handle errors
if (response.success === false) {
console.error('Error in AJAX response:', response.data);
return { results: [] };
}
return {
results: response.data,
pagination: {
more: (params.page * 30) < response.total_count
}
};
},
cache: true,
error: function(jqXHR, textStatus, errorThrown) {
console.error('AJAX error:', textStatus, errorThrown);
}
},
placeholder: 'Search for a ' + ajaxAction.split('_')[1],
minimumInputLength: 0,
width: '100%'
});
}
// Initialize autocomplete for the fields
setupAutocomplete($('[name="tags"]'), 'get_tags_suggestions');
setupAutocomplete($('[name="categories"]'), 'get_categories_suggestions');
setupAutocomplete($('[name="taxonomies"]'), 'get_taxonomies_suggestions');
setupAutocomplete($('[name="authors"]'), 'get_authors_suggestions');
});
Enqueue Scripts and Localize AJAX URL:
function enqueue_admin_scripts() {
// Load Select2
wp_enqueue_script('select2', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js', array('jquery'), '4.0.13', true);
wp_enqueue_style('select2', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css', array(), '4.0.13');
// Load custom JS
wp_enqueue_script('custom-admin-js', get_template_directory_uri() . '/js/custom-admin.js', array('jquery', 'select2'), '1.0', true);
wp_localize_script('custom-admin-js', 'my_ajax_object', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('my_nonce')
));
}
add_action('admin_enqueue_scripts', 'enqueue_admin_scripts');
Problem:
The JavaScript seems to be setting up the Select2 fields correctly, and I see the log messages in the console. However, the autocomplete feature is not working as expected, and the AJAX requests don’t seem to be reaching the server or returning the expected results.
What I’ve Checked:
- The PHP functions are hooked correctly to wp_ajax_ actions.
- The
my_ajax_object
variable is defined and passed to the JavaScript. - Debug logs in the PHP functions indicate they are not being called.
Questions:
- Am I missing something in the AJAX request setup?
- How can I ensure the AJAX requests are being sent and received correctly?
- Are there any common pitfalls or issues with using Select2 and AJAX in WordPress admin that I should be aware of?
I’ve tried to read the answers to similar questions here, and yet I can’t seem to figure out how to properly implement them here in my situation.
Any help or pointers would be greatly appreciated. Thank you!
1
Is your nonce, correct?
I see you use: my_ajax_object.nonce and ajaxurl without my_ajax_object as in:(my_ajax_object.ajaxurl)
1