Reputation: 339
I want to use this jquery plugin to get values from database...
I create jquery ajax code and HTML to get values from database:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link href="http://ivaynberg.github.com/select2/select2-3.3.2/select2.css" rel="stylesheet" type="text/css" />
<script src="http://ivaynberg.github.com/select2/select2-3.3.2/select2.js"></script>
</head>
<body>
<select id="test" style="width:200px;">
<option value=""><option>
</select>
<script>
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
}
});
</script>
</body>
and json.php code:
<?php
$pdo=new PDO("mysql:dbname=ddd;host=localhost","ddd","ddd");
$statement=$pdo->prepare("SELECT id,ime_prezime FROM radnici");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
when I run php code i get json:
[{"id":"1","ime_prezime":"Pera Peric"}]
s the problem is not with php code... what is wrong in my html/jquery code?
I dont get anything, I cant fetch values from json.php file
UPDATE:
I find error is was json format, but now I cant save values that I get , so when I click values just disapear...
<input id="test" style="width:300px;">
<select multiple id="test" style="width:300px"></select>
<script>
function formatValues(data) {
return data.ime_prezime;
}
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
},
formatResult: formatValues
});
</script>
Upvotes: 1
Views: 2583
Reputation: 15550
You need to return id
, text
pair and use following structure;
<input type="hidden" name="test" id="test" style="width:200px;"/>
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
}
});
You can see demo here: http://jsfiddle.net/huseyinbabal/68fD2/1/ . In demo, I have used local data, but it works with your ajax code like above.
Edit:
If you want to do that as in your demo, you can use following;
function formatValues(data) {
return data.ime_prezime;
}
var test = $('#test');
var data = [{"id":"1","ime_prezime":"Pera Peric"},
{"id":"2","ime_prezime":"Something else"},
{"id":"3","ime_prezime":"Lorem"},
{"id":"4","ime_prezime":"Ipsum"}
];
$(test).select2({
data:{results: data, text: 'ime_prezime'},
width: "300px",
formatResult: formatValues,
formatSelection: formatValues,
multiple: true
});
Here is a working demo: http://jsfiddle.net/huseyinbabal/68fD2/6/
Upvotes: 1