Reputation: 51
I am trying to use the jQuery UI autocomplete widget but without success. There is no list of matches presented.
My script is as follows:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="./jquery-1.11/jquery-1.11.1.min.js"></script>
<script src="./jquery-ui-1.11.1/jquery-ui.min.js"></script>
<script>
$("#tags").autocomplete({
source: function( request, response ) {
$.ajax({
url: "testAJAX.php",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
response(data);
}
});
}
});
</script>
</head>
<body>
<input type="text" id ="tags" />
</body>
</html>
On the server my PHP code is as follows:
<?php include "dbConnect.php";
header('Content-type: application/json');
$q=$_POST["term"];
$sql="SELECT name, id as value, id FROM sample WHERE id LIKE '".strtoupper($q)."%';";
$result = mysqli_query($con, $sql);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
$json = json_encode($rows);
echo $json;
I have checked that the AJAX and JSON is working by using the following JQuery script that does output the values from the php.
<script>
$(document).ready(function(){
$('#path').keyup(function(){
var t = $('#path').val();
$.ajax({
type: "POST",
url: "testAJAX.php",
data: {term: t},
dataType: 'json',
success: function( data ) {
$('#tags').html('');
for (var i in data) {
$('#tags').append(data[i].value + '<br/>');
}
}
});
});
});
</script>
</head>
<body>
<input type="text" id="path" />
<div id="tags">
</div>
</body>
</html>
Upvotes: 2
Views: 10192
Reputation:
Jquery Autocomplete (Get method,Linq,Json) Works 100%
Javascript
$(function () {
$("#SearchFirst").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Admin/GetItemList",
dataType: "json",
data: { term: request.term },
success: function (data) {
response(data);
}
});
}
});
});
C#
public ActionResult GetItemList()
{
var search = Request.Params["term"];
var itemList = (from items in db.TblItems where items.ItemName.StartsWith(search) select new { label = items.ItemName, value = items.ItemName }).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
Upvotes: 0
Reputation: 51
I worked it out; I hadn't put the autocomplete in a $(function(){}) block.
So it should be:
$(function(){
$("#tags").autocomplete({
source: function( request, response ) {
$.ajax({
url: "testAJAX.php",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
response(data);
}
});
}
});
});
Upvotes: 3