Ivan
Ivan

Reputation: 2481

Render HTML of an AJAX response

I'm using Select2 AJAX remote option to fetch data:

$('#t').select2({
    ajax: {
        url: '../ajax/results.php',
        data: function (params) {
            return {
                search: params.term,
                page: params.page || 1
            };
        }
    }
});

So far so good, result are returned like this (please notice the <small> tag):

{
    "results": [
        {
            "id": "1",
            "text": "Doe Joe, <small>Mr.</small>"
        },
        {
            "id": "2",
            "text": "Smith Anne, <small>Mrs.</small>"
        },
        {
            "id": "3",
            "text": "Rossi Mario, <small>Mr.</small>"
        },
        ...
     ],
     "pagination": {
         "more": false
     }
}

In the <select>, the <small> tag is printed as-is, instead of being parsed. Select2 docs says that HTML are not rendered by default and that the rendered result must be wrapped in a jQuery object to work, but no further example is given.

All the examples that involve templateResult, indeed, does not give feedback on how to pass AJAX result (i.e. https://select2.org/dropdown#templating )

Please, any help?

Upvotes: 1

Views: 1406

Answers (1)

Ivan
Ivan

Reputation: 2481

The templating example is right, I just need to wrap everything in a <span> tag for it to work:

function formatItem (item) {
    if (!item.id) {
        return item.text;
    }
    return $('<span>' + item.text + '</span>');
}

$('#t').select2({
    ajax: {
        url: '../ajax/results.php',
        data: function (params) {
            return {
                search: params.term,
                page: params.page || 1
            };
        }
    },
    templateResult: formatItem,
    templateSelection: formatItem
});

Upvotes: 2

Related Questions