How to use source: function()... and AJAX in JQuery UI autocomplete
$("#id").autocomplete(
{
search: function () {},
source: function (request, response)
{
$.ajax(
{
url: ,
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
}
});
},
minLength: 2,
select: function (event, ui)
{
var test = ui.item ? ui.item.id : 0;
if (test > 0)
{
alert(test);
}
}
});
This is completely new working code with sample AJAX call.
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<div>
<div id="project-label">Select a project (type "j" for a start):</div>
<img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
<input id="project" />
<input type="hidden" id="project-i" />
</div>
@*Auto Complete*@
<script>
$(function () {
$("#project").autocomplete({
minLength: 0,
source : function( request, response ) {
$.ajax({
url: "http://jsonplaceholder.typicode.com/posts/1/comments",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
response( data );
}
});
},
focus: function (event, ui) {
$("#project").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#project").val(ui.item.name);
$("#project-id").val(ui.item.email);
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a> " + item.name + "<br>" + item.email + "</a>")
.appendTo(ul);
};
});
</script>
Inside your AJAX callback you need to call the response
function; passing the array that contains items to display.
jQuery("input.suggest-user").autocomplete({
source: function (request, response) {
jQuery.get("usernames.action", {
query: request.term
}, function (data) {
// assuming data is a JavaScript array such as
// ["[email protected]", "[email protected]","[email protected]"]
// and not a string
response(data);
});
},
minLength: 3
});
If the response JSON does not match the formats accepted by jQuery UI autocomplete then you must transform the result inside the AJAX callback before passing it to the response callback. See this question and the accepted answer.
Try this code. You can use $.get
instead of $.ajax
$( "input.suggest-user" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'Get',
url: 'yourURL',
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
// hide loading image
response( $.map( data, function(item) {
// your operation on data
}));
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3,
open: function() {},
close: function() {},
focus: function(event,ui) {},
select: function(event, ui) {}
});