Select2 use a dynamic Ajax URL on call
Asked Answered
B

3

16

I use the Select2 plugin (v 3.5.2) with Ajax to dynamically load elements in the list.

I have an issue as between the initialization of the Select2 (where a url property is set in the ajax helper) and the time the ajax call is made, this url might need to be changed.

So I have something like this :

$box.select2({
    containerCssClass: "form-control"
    minimumInputLength: 0,
    allowClear: true,
    ajax: {
       url: someUrl,
       dataType: 'json',
       quietMillis: 100,
...
}

I can't figure out how, when, where to change the ajax.url value before it launches.

The help of Select2 says:

Select2 uses jQuery's $.ajax function to execute the remote call by default. An alternative transport function can be specified in the ajax settings, or an entirely custom implementation can be built by providing a custom query function instead of using the ajax helper.

But I can't find any example on how to do it.

Thanks in advance for any help. Much appreciated.

Beaton answered 21/5, 2015 at 12:14 Comment(0)
B
30

I can't figure out how, when, where to change the ajax.url value before it launches.

The ajax.url option can be specified as a static string or a method returning one in both Select2 3.5.x and 4.0.0.

$("select").select2({
  ajax: {
    url: function () {
      return UrlHelper.RemoteAPI();
    }
  }
});

This is useful for changing the base URL, for example when the URL is determined at runtime or is automatically generated in a different method. If you need to change the query parameters, such as the one used for sending the search term, you need to override the ajax.data option.

$("select").select2({
  ajax: {
    data: function (args) {
      // args is the search term in 3.5.x

      // args is an object containing the query parameters in 4.0.0
      // args.term is the search term in 4.0.0
      return {
        search: args.term || args;
      };
    }
  }
});

The data here will be appended as query parameters by default, and will be sent as the request body if the method type is changed from GET (the default) to anything else.

Select2 uses jQuery's $.ajax function to execute the remote call by default. An alternative transport function can be specified in the ajax settings, or an entirely custom implementation can be built by providing a custom query function instead of using the ajax helper.

But I can't find any example on how to do it.

Select2 does allow for a different AJAX transport to be used by changing the ajax.transport option.

In 3.5.2, this must be a $.ajax-compatible method, so it must be able to take an object containing the success and failure callbacks.

$("select").select2({
  ajax: {
    transport: function (args) {
      // args.success is a callback
      // args.failure is a callback

      // should return an object which has an `abort` method.
      return $.ajax(args);
    }
  }
});

In 4.0.0, this must be a method which takes a params object (the same one passed to ajax.data), a success callback, and a failure callback.

$("select").select2({
  ajax: {
    transport: function (params, success, failure) {
      var $request = $.ajax(params);

      $request.then(success);
      $request.fail(failure);

      return $request;
    }
  }
});
Burdette answered 21/5, 2015 at 13:22 Comment(2)
You saved my life.Dhammapada
You also saved my life.Macaulay
A
4

Very Simple Javascript code to handle the same, can be used in Suitescript(Netsuite) also.

// prepare your dynamic URL inside this method and return
function getURL() {
     return url + params;
}

// While binding the select2 with the dropdown set url to call a anonymous function which internally calls another function.
jQuery("select.itemDropDown").select2({
    placeholder: "Select an item",
    width: "200px",
    minimumInputLength: 3,
    ajax: {
        url: function() {
            return getURL()
        },
        dataType: 'json'
    }
});
Astaire answered 15/12, 2017 at 5:28 Comment(0)
G
0

As mentioned before you can use a function to dynamically generate the URL, in this example I am adding the search parameter as part of the URL.

 $(document).ready(function() {
            $('#country-select').select2({
                minimumInputLength: 1,
                ajax: {
                    url: function (params) {
                        return 'https://restcountries.com/v3.1/name/' + encodeURIComponent(params.term) + '?fullText=false';
                    },
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            name: params.term,
                            fullText: true
                        };
                    },
                    processResults: function (data) {
                        return {
                            results: $.map(data, function (country) {
                                return {
                                    id: country.name.common,
                                    text: country.name.common
                                }
                            })
                        };
                    },
                    cache: true
                },
                placeholder: 'Select a country',
                allowClear: true
            });
        });
.select2-container {
            width: 250px !important ;
        }
<!DOCTYPE html>
<html>
<head>
    <title>Country Selector</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/css/select2.min.css"  />
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js" ></script>

</head>
<body>
    <select id="country-select"></select>
</body>
</html>
Goldia answered 8/5, 2023 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.