Support

Account

Home Forums ACF PRO Select2 results not showing using js/api select2_ajax_results filter Reply To: Select2 results not showing using js/api select2_ajax_results filter

  • I spotted an issue with my original javascript, I was returning to early at the end of my script, so my ajax request would of have not completed by the time this end return was hit.

    So I’ve fixed this issue using this code below…

    // select2 ajax results filter
    acf.add_filter('select2_ajax_results', function( json, params, instance ){
    
        // if field id is packaging options select (second select field)
        if(instance.data.field.data.key === 'field_60cd1751993d1') {
    
            // get the current post id value of the previous select field
            let post_id = instance.data.field.$el.prev('.acf-field-select').find('SELECT').val();
    
            // if we got post id else false
            if(post_id) {
                post_id = parseInt(post_id);
            } else {
                post_id = false;
            }
    
            // jquery ajax call
            $.ajax({
                cache: false,
                timeout: 30000,
                url: ajaxurl,
                type: 'GET',
                data: {
                    action: 'get_packaging_options',
                    post_id: post_id
                },
                dataType: 'json',
                success: function (response) {
    
                    // add our array to json results array
                    json.results = response.data;
             
                }
             }).then(function () {
    
                // log our updated json
                console.log(json);
    
                // return updated json
                return json;
    
            });
    
        } else {
    
            // log our default json
            console.log(json);
    
            // return default json
            return json;
    
        }
    
    });

    So now when I click on my second select2 field, this is the updated json console log…

    {
      limit: 0,
      more: false,
      results: Array(6)
        0: {id: "60cd5553b7a86", text: "Green"}
        1: {id: "60cd5565b7a87", text: "Orange"}
        2: {id: "60cd556db7a88", text: "Yellow"}
        3: {id: "60cd5575b7a89", text: "Blue"}
        4: {id: "60cd5586b7a8a", text: "Cyan"}
        5: {id: "60cd558cb7a8b", text: "Red"}
        length: 6
    }

    Log looks good, but instead of the the select2 dropdown saying No Results Found, it now says Searching…

    But still my results are not loading?