Reputation: 1
I am new to jquery. I am trying to put together autocomplete feature for a text field. So far I am able to take the input, make a ajax call, get the json response and build an array with data . However, I am unable to present in that data in autocomplete. Here is my javascript code. I am not sure if its a css issue or a javascript issue. I have added jquery-ui.css. Please advise.
$(document).ready(function() {
function SearchText() {
$("#text-drug").autocomplete({
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "url",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
},
success: function (data) {
if (data != null) {
var parsedJson = $.parseJSON(data);
alert(parsedJson);
var arr = [];
for (var i=0;i<parsedJson.length;++i)
{
arr.push(parsedJson[i].name);
}
alert(arr);
response(arr); }
},
error: function(result) {
alert("Error");
}
});
}
});
}
});
Upvotes: 0
Views: 106
Reputation:
Here's a similar code I tested and it works fine. Please see if it helps you to find the issue with your code.
1. index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete functionality</title>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#txtAutocomplete" ).autocomplete({
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "data.php",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
},
success: function (data) {
if (data != null) {
var parsedJson = $.parseJSON(data);
//alert(parsedJson);
var arr = [];
for (var i=0;i<parsedJson.length;++i)
{
arr.push(parsedJson[i].name);
}
//alert(arr);
response(arr); }
},
error: function(result) {
alert("Error");
}
});
}
});
});
</script>
</head>
<body>
<!-- HTML -->
<div class="ui-widget">
<input id="txtAutocomplete">
</div>
</body>
</html>
2. data.php
<?php
echo "[{\"name\":\"programmer\"},{\"name\":\"stackoverflow\"}]";
?>
Output
You may also need to filter data using term property in request object. Please refer to JQuery UI Autocomplete Documentation for more information.
Upvotes: 1