Max Krizh
Max Krizh

Reputation: 595

Select2 with AJAX: select disappears after recieving AJAX results

I have reviewed many questions and answers here, but the problem still persists. This is my select (one of them):

<div class="col-md-2">
    <label for="wh_location">{{ __('reports.warehouse_movement.location') }}</label>
    <div class="input-group">
        <select name="wh_location" id="wh_location" class="form-control select2" multiple></select>
    </div>
</div>

And then it goes:

$(document).ready(() => {
  $('.select2').select2(); // For Non-AJAX select2 boxes;

  $('#wh_location').select2({
  minimumInputLength: 3, // Commenting this out will show all results at once, but if you try to search, all results disapper;
  delay: 500,
  allowClear: true,
  minimumResultsForSearch: -1,
  ajax: {
    url: '{{ route('rpc.report', ['WarehouseMovement', 'getLocationsList']) }}',
    dataType: 'json',
    method: 'post',
    delay: 500,
  }
});

The problem is that after searching for a value, it shows "Searching" and then the select dropdown disappears completely. Inspecting it in element, it shows an empty UL tag:

Here it is

My backend (PHP) is returning correct JSON format, so no need for processResults callback function in the AJAX (although I tried this as well):

{"results":{"35":{"id":"750","text":"750 Test1"},"137":{"id":"750","text":"750 Test OLD"},"166":{"id":"750","text":"750 Test New"}}}

I've already checked everything, so:

  1. The ID value is unique;
  2. All other select2 boxes work without any problem with the SAME EXACT code;
  3. processResults callback and returning an array from PHP does nothing;
  4. PHP returns the same exact format as for all other select2 boxes;
  5. Select2 is being rendered and worked fine without AJAX;
  6. Maybe there's some kind of limit of select2 boxes? I tried disabling all of them, except this one - nothing changed;
  7. The select2 is being loaded from here: <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.js"></script>

What am I missing here? I've ran into the same problem couple of days ago, but then I decided just to ditch that field.

Upvotes: 0

Views: 192

Answers (1)

Max Krizh
Max Krizh

Reputation: 595

Found the solution to my own problem. As it seems, PHP should return array of objects in the "results" section.

So my previous return code was:

{"results":{"35":{"id":"750","text":"750 Test1"},"137":{"id":"750","text":"750 Test OLD"},"166":{"id":"750","text":"750 Test New"}}}

But it should be as follows (notice the array, not the objects after the "results"):

{"results":[{"id":"750","text":"750 Test1"},{"id":"750","text":"750 Test OLD"},{"id":"750","text":"750 Test New"}]}

Upvotes: 1

Related Questions