Reputation: 1942
i am trying to ajax remote data for select2(using 4.0.6-rc.1), tried a few examples, at first the q parameter was undefined but i solved it and now the select is not giving me the results,don't know how to format the json data tried the following and getting the following error in the console:
$('#compose_username').select2({
dropdownParent: $("#modal-compose"),
placeholder: "Search country here...",
ajax: {
url: "username.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: false
},
// escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo(repo) {
if (repo.loading) return repo.text;
return repo.desc;
}
function formatRepoSelection(repo) {
return repo.desc || repo.text;
}
USERNAME.PHP
include('../core/config.php');
try {
$stmt = $db_con->query("SELECT id,username FROM users WHERE username LIKE '%".$_GET['q']."%' LIMIT 10");
$stmt->execute();
$json = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$json[] = ['id'=>$row['id'], 'username'=>$row['username']];
}
echo json_encode($json);
} catch(PDOException $e) {
echo $e->getMessage();
}
JSON DATA:
if i type a
then getting the following in console but no option is showing in select2
(3) [{…}, {…}, {…}]
0
:
{id: "1", username: "admin"}
1
:
{id: "29", username: "adil3310"}
2
:
{id: "30", username: "asdsad"}
length
:
3
__proto__
:
Array(0)
Upvotes: 0
Views: 723
Reputation: 1942
After a lot of struggle ,i managed to get it working ,the reason i was trying to Parse Json data and it was already parsed so i used it and it works. Full working example below ,that may help others:
$('#compose_username').select2({
// SET THIS IF SELECT IS IN A MODAL
dropdownParent: $("#modal-compose") ,
placeholder: "Search country here...",
// MINIMUM INPUT TO SEARCH BEFORE
minimumInputLength: 3,
ajax: {
url: "username.php",
dataType: 'json',
delay: 250,
cache: false,
data: function (params) {
$('#compose_username').val(null).trigger('change');
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, page) {
console.log(data);
var result = $.map(data, function (item) { return { id: item.id, text: item.username }});
return { results: result };
}
}
});
PHP( FOR GETTING LIST OF USERNAME, we can set limit at the query)
try{
$stmt = $db_con->query("SELECT id,username FROM users WHERE username LIKE '%".$_GET['q']."%' LIMIT 10");
$stmt->execute();
$json = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$json[] = ['id'=>$row['id'], 'username'=>$row['username']];
}
echo json_encode($json);
}
catch(PDOException $e){
echo $e->getMessage();
}
Upvotes: 1