Reputation: 27
i am trying to display some field data from table mysql into the select2 option but whatever i do it still shows me only one. This is how I expected: Screenshot Any suggestions? Thanks
in javascript file I have this code
<script type="text/javascript">
//List ajax for list product
$(".js-productList").select2({
ajax: {
url: "halaman/hal_search2ajax/productsList.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function(data){
return { results: data };
},
cache: true
},
minimumInputLength: 3,
});
</script>
my code in html
<select name='item' class=\"js-productList form-control\" required></select>
Code in productList.php
<?php
// connect to database
require('../../config/koneksi.php');
$q = $_POST['q'];
$sql = mysql_query("select id_item as id, item_name as text, item_code as code from item where item_name like '%".$q."%'");
$num = mysql_num_rows($sql);
if($num > 0){
while($data = mysql_fetch_assoc($sql)){
//I want to show the item_name and item_code
$tmp[] = $data;
}
} else $tmp = array();
echo json_encode($tmp);
?>
Upvotes: 1
Views: 726
Reputation: 2708
You just need to manipulate response return by ajax call using map() function
try like this
$(".js-productList").select2({
ajax: {
url: "halaman/hal_search2ajax/productsList.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function(data){
output = $.map(data, function (obj) {
obj.text = obj.text + "-" + obj.code
return obj;
});
return { results: output };
},
cache: true
},
minimumInputLength: 3,
});
Here is working example https://jsfiddle.net/6tzkLtvL/2/
I hope it will help you.
Upvotes: 1
Reputation: 471
Something like this. Seems to be the typical parse json. I prefer tu use $.post:
<select name='item' id="itemselect" class=\"js-productList form-control\" required></select>
var data = {
q: params.term // or the way you obtain them
}
$.post('halaman/hal_search2ajax/productsList.php', data, function(response) {
$.each(response,function(i,item){
$('#itemselect').append($('<option>', {
value: item.code,
text : item.code
}));
}
}, 'json');
with append it understand what goes into value and the text
<option value="'+value+'">'+text+'</option>
Upvotes: 1