Issues Implementing AJAX Autocomplete in WordPress Admin with Select2

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:

  1. Am I missing something in the AJAX request setup?
  2. How can I ensure the AJAX requests are being sent and received correctly?
  3. 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật