ClearBoth
ClearBoth

Reputation: 2325

Select2 not loading data into after ajax call

I am trying to use jquery select2 to load data using ajax. Everything seems to be right, except the data is not showing after a success ajax call. Here is the code:

$(document).ready(function()
{
    $("#program").select2({
        placeholder: "Select a Program",
        minimumInputLength: 3,
        ajax: {
            url: "ajax.php",
            dataType: 'json',
            quietMillis: 200,
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    page: page // page number
            };
            },
            results: function (data) {
                return {results: data};
            }
        },
        dropdownCssClass: "bigdrop",
        escapeMarkup: function (m) { return m; }
    });
});

Ajax code:

$search = $mtc->pure['term'];

$programs = $mtc->db->query("SELECT * FROM program AS program 
    WHERE programcode LIKE '%$search%' OR title_en LIKE '%$search%' OR title_ar LIKE '%$search%'
");

while ($program = $mtc->db->fetch_array($programs)){

    $data[] = array("text" => $program['programcode'].' '.$program['title_en'], "id" => $program['programid']);
}

$count = number_format($mtc->db->num_rows($programs));

unset($programs);
echo json_encode(array('data' => $data));

HTML:

<div class="field-block button-height">
    <label for="program" class="label"><b>Program</b></label>
    <input type="hidden" id="program" class="width-300">
</div>

the returned data is as follow:

{"data":[{"text":"MG 101 Negotiation Skills and The Art of Persuasion","id":"1"},
{"text":"MG 102 Balanced Score Card","id":"2"},
{"text":"MG 103 Effective Manager... Skills and Behaviors","id":"3"},
{"text":"MG 104 Building High-Performance Teams","id":"4"},
{"text":"MG 105 Measuring Institutional Performance Using RADAR","id":"5"},
{"text":"MG 106 How to Be a Distinctive Administrative Leader","id":"6"},
{"text":"MG 107 Organizational Excellence Between Requirements and Results","id":"7"},
{"text":"MG 108 Effective Negotiation.. Skills and Techniques","id":"8"},
{"text":"MG 109 Developing Personal Skills for Manager","id":"9"}]}

I looked into other questions but I did not find any solution. I don't know where is the error in my code.

Upvotes: 1

Views: 1282

Answers (1)

ClearBoth
ClearBoth

Reputation: 2325

The stupid problem was in PHP code:

echo json_encode(array('data' => $data));

It's suppose to be:

echo json_encode($data);

Upvotes: 1

Related Questions