Home > Mobile >  bootstrap-select doesn't populate from AJAX call
bootstrap-select doesn't populate from AJAX call

Time:08-29

I am trying to populate a bootstrap-select control using the following AJAX call:

    function loadCategories() {
        $.ajax({
            url: '../handlers/getcategorylist.ashx',
            data: null,
            method: 'post',
            dataType: 'json',
            success: function (data) {
                alert(JSON.stringify(data));
                $('#ddlCategories').html(JSON.stringify(data));
                $('#ddlCategories').selectpicker('refresh');
            },
            error: function (e) {
                console.log(e.responseText);
            }
        });
    }

The HTML for the bootstrap-select is as follows:

                        <div >
                            <div >
                                <select id="ddlCategories" name="ddlCategories" data-width="25%" >
                                    <option value="select">Select From The List</option>
                                 </select>
                            </div>
                        </div>

The AJAX call executes and is successful. Using JSON.stringify() I get the following data back (shown in an alert):

alert window showing data returned from AJAX call

For whatever reason, the bootstrap-select doesn't populate. It displays empty. What am I missing here?

CodePudding user response:

Hi it seems like you're setting the inner HTML of your select element to a array of objects. You probably have to .forEach() through all the objects inside of your response array and append them to the select element (like described in the following StackOverflow answer. If you'd also like to remove existing content from the select element consider setting the html to blank.

So something along the lines of:

data.forEach(entry => {
    $('#ddlCategories').append(`<option value=${entry['ID']}> ${entry['Name']} </option>`);
});
  • Related