Support

Account

Home Forums Backend Issues (wp-admin) Reload values in select2 with ajax

Solving

Reload values in select2 with ajax

  • Hi,

    I’m looking for a method to reload the data in my select2, realtime with ajax.

    Right now i have:

      function __construct()
      {
        $this->name     = 'documentapi';
        $this->label    = __("Document API", 'acf');
        $this->category = 'relational';
        $this->defaults = array('allow_null' => 0, 'multiple' => 0, 'ui' => 1, 'language' => 'nl-BE');
    
        add_action('wp_ajax_acf/fields/documentapi/query', array($this, 'ajax_query'));
        add_action('wp_ajax_nopriv_acf/fields/documentapi/query', array($this, 'ajax_query'));
    
        parent::__construct();
      }
    
      private function get_choices($options = array())
      {
        if (empty($options['s']) || empty($options['field_key'])) {
          return;
        }
        $language = isset($options['language']) ? $options['language'] : $this->defaults['language'];
    
        $fetcher = $this->getDocumentFetcherFor($language);
    
        $r = [];
        foreach ($fetcher->search($options['s']) as $document) {
          $r[] = ['id' => $document['id'], 'text' => $document['title']];
        }
    
        return $r;
      }
    
      public function ajax_query()
      {
        if (!acf_verify_ajax()) {
          die();
        }
        echo json_encode($this->get_choices($_POST));
        die();
      }

    In my javascript i empty the select2 values on a language taxonomy field change, this works fine:

     $(function() {
        $(document).ready(function() {
          // Empty documents(s) when you change language in radiobutton
          $('.acf-taxonomy-field[data-taxonomy="languages"] input:radio').change(function() {
            $('tr.acf-field-documentapi .select2-container').select2('val', '');
          });
        });
      });
    

    On this “onchange” event I’d like to “repopulate” the select2 with new data (realtime with ajax), based on the current selected language.

    I tried select2’s updateResults but did not have any luck..

    Can anyone help me out?

    I’m using AFC 5.3.0

  • Nevermind, solved it (can’t find delete button).

  • @paulhuisman Okay great 🙂

    Something that would be even better is if you post your solution and set it as the answer to this topic! That way the topic is closed properly and your post might help others in the future!

    Thanks!

  • @paulhuisman how did you solve this?
    please let me know.

  • @paulhuisman I am trying to solve this problem myself. Would be great if you posted your solution.

  • I found out that the select2 can be refreshed by calling the change.select2.

    
    var field = acf.getField('acf-field-key');
    var $select = field.$el.find('select');
    
    // Could also be jQuery collection, optgroup elements or HTML string if working
    const newOptions = [
        new Option('New label', 'new-value'),
        new Option('Another option', 'another-value')
    ];
    
    // Clear previous elements
    $select.empty();
    
    // Add new options to select element
    $select.append(newOptions);
    
    // Set a new selected option
    $select.val('new-value');
    
    // Refresh select2
    $select.trigger('change.select2');
    

    You can of course keep or alter previous elements, instead of removing them. I guess you could do pretty much anything before triggering the change.select2 event.

    I hope the JavaScript API will update in the future to a non jQuery solution

Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Reload values in select2 with ajax’ is closed to new replies.