How do i add tags if there is a server error?

So this is my code

        placeholder: "Palabras Clave",
        ajax: {
            url: '/cotizacion/buscartags',
            data: function (params) {
                var query = {
                    q: params.term,
                return query;
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.Tag,
                            id: item.Tag,
                            data: item
        minimumInputLength: 3,
        maximumSelectionLength: 5,
        tags: true,
        tokenSeparators: ['|'],
        language:  {
            // You can find all of the options in the language files provided in the
            // build. They all must be functions that return the string that should be
            // displayed.
            inputTooShort: function () {
                return "Introduzca un minimo de tres caracteres";
            searching: function () {
                return "Buscando";

If the server throws an error lets say a 500 i get this legend “the results could not be loaded”, and that’s it i just need to add whatever the user is searching for, the behavior is different from “no tags found” to server error, i’m without a clue on how to do this, thanks in advance.

It sounds like you need to intercept the failure response, rather than letting Select2’s default error handling code execute. You’re using the default transport, which is jQuery’s ajax() method. You can pass several options to that method, including an error handler.

Alternatively, you could define your own transport method, as shown in the example on the Select2 AJAX documentation page. (Note that the example uses $.ajax(), but also shows how to call success and error handlers. In your case, you would want to pass your own error handling function in $ rather than the error handler Select2 will provide to your custom transport method.)

In either of the approaches above, you would want your error handler to ignore the error and “stuff” the underlying HTML <select> with a selected <option> containing the user’s query term (i.e., the value of the “tag”). Then trigger the “change”/ to update the Select2. (See for details.)

(Note that I’m sort of making this up—I’ve never had to deal with this situation. So what I’ve suggested above might not work without some additional tinkering. But I hope it will get you started toward a solution, at least.)

1 Like


If possible I would like to re-open this request : I can’t get my custom ajax error handler to show an empty list insted of the error message.
Did anyone ever find a viable solution ?