0

I have a form where the country states have to be displayed in a dropdown, since there was autocomplete already added, I'm getting the response as array in "console.log(data)" but only when I search a state, however I'm unable to change the autocomplete to selection list, I did attempt by changing jquery autocomplete to use select2,selectmenu or on change, but this only works with autocomplete. I do not require the autocomplete search at all but just the dropdown with the country states to be listed from data. below is the code where I'm using a ajax post to get the response using a api call from php file. how do I get the list of country states in selection list and trigger an event when selected, I'm a newbie in this domain.

Some of the sources that I followed,

    ('#country_state').autocomplete({
    source: function(request, response) {
      Request.AbortAll();
      $.ajax({
          type: "POST",
          minLength: 3,
          url: base_path + "countrystatelist.php",
          dataType: "json",
          data: {
            q: request.term
          },
          beforeSend: function (jqXHR, settings) {
            Request.List.push(jqXHR);
            
        },
          success: function(data) {
            response(data);
            console.log(data);
          }
        });
    },
    select: function(event, ui) {
      $('#country_state').attr('country_state-id', ui.item.id);
    }
    });
  • php -
    public function AllState() {
    $results = [];   
    $Country_states_info = CountryState::GetAllStates(); /* from api */
    foreach ($Country_states_info as $country_state) {
      if (!isset($country_state['name'])) {
        continue;
      }
        $results[] = [
          'value' => $country_state_name,
          'label' => $country_state_name,
          'id' => $country_state['id'],
        ];
         }
    return new JsonResponse($results);
  }

using select2

jQuery('#country_state').select2({

   source: function(request, response) {
        Request.AbortAll();
        jQuery.ajax({
            type: "POST",
            minLength: 3,
            url: base_path + "countrylist.php",
            dataType: "json",
            data: {
              q: request.term
            },
            beforeSend: function (jqXHR, settings) {
              Request.List.push(jqXHR);
               
          },
            success: function(data) {
                 // response(data);
            
                return {
                    results: data.items
                  };
            
  
              console.log(data);
            }

            
          });
      },

      select: function(event, ui) {
        $('#country_state').attr('country_state-id', ui.item.id);
        }
    
        });
  • What happened when you tried select2? That's a decent library for filtering dropdown lists – Rylee Aug 15 '22 at 03:38
  • Well even with select2, the dropdown is not getting populated from json. seems something is missing. – Jeff_dan13 Aug 15 '22 at 04:01
  • Are you sure you've got select2 setup correctly? There's specific settings for ajax data as well as an expected type and format of the data. – Rylee Aug 15 '22 at 04:04
  • I added the select2 script in above edit, did not change much except on success. – Jeff_dan13 Aug 15 '22 at 04:11
  • What's the format of the response `data`? If it's to work with that code, it would need to be something very similar to `{ items: [{ id: 1, text: "Option 1" }, { id: 2, text: "Option 2" }] }`. You also wouldn't use `source: {...`, you would use `ajax: {...`. Have you read the [docs](https://select2.org/data-sources/ajax)? – Rylee Aug 15 '22 at 04:16
  • Welcome to Stack Overflow. There appears to be a discrepancy in your PHP. `$country_state_name` does not appear to be defined any place. – Twisty Aug 15 '22 at 17:46
  • is there a way to just convert autocomplete to select list? or having select list without searching for a term but just to list all the country states. – Jeff_dan13 Aug 16 '22 at 08:47

1 Answers1

0

Would suggest the following updates to your PHP.

public function AllState() {
  $results = [];   
  $Country_states_info = CountryState::GetAllStates(); /* from api */
  foreach ($Country_states_info as $country_state) {
    if (!isset($country_state['name'])) {
      continue;
    }
    array_push($results, [
      'value' => $country_state['name'],
      'label' => $country_state['name'],
      'id' => $country_state['id'],
    ]);
  }
  return new JsonResponse($results);
}

I did not see where $country_state_name was defined. I suspect you meant $country_state['name'].

Twisty
  • 30,304
  • 2
  • 26
  • 45