Select2 use a dynamic Ajax URL on call

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;
    }
  }
});

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'
    }
});