Reputation: 71
I have here autocomplete script with ajax functions. I tried to get the data from database through ajax but why isn't working?
Here's my code below.. Any help will appreciate !
Html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: function(request, response) {
$.getJSON("autocomplete.php", { app_cn: request.term }, response);
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
Autocomplete.php
<?php
include('connect1.php');
if(isset($_GET["app_cn"])) {
$auto = $mysqli1->real_escape_string($_GET["app_cn"]);
//$selected = $mysqli1->real_escape_string($_GET["selected"]);
$sql = $mysqli1->query("SELECT id,item FROM code WHERE item LIKE '%$auto%' GROUP BY item ORDER BY id");
if($sql)
{
$str = array();
while($row = $sql->fetch_assoc())
{
$str[] = $row['item'];
}
echo json_encode($str);
}
}
?>
Upvotes: 1
Views: 86
Reputation: 12117
You should use success callback function in $.getJSON
, and pass into response variable try this code
<script>
$(function() {
$( "#tags" ).autocomplete({
source: function(request, response) {
$.getJSON("autocomplete.php", { app_cn: request.term }, function(data){
response(data);
});
}
});
});
</script>
AND in php script
$str = array();
while($row = $sql->fetch_assoc())
{
array_push($str, array(
"id" => $row['id'],
"label" => $row['item'],
"value" => $row['item']
));
}
header("Content-type: text/json");
echo json_encode($str);
Upvotes: 1
Reputation: 3973
in your console if you dont see any errors take a look at what the response is. If the response is empty add :
header('Content-Type: application/json');
just before echo json_encode($str);
$.getJSON requires the header to be application/json
Upvotes: 1