I change the autocomplete data source to my php file, and I have tried the code below. But it’s not work, could someone suggest how to fix it?
Thanks
$('#search').autocomplete({
source: function( request, response ) {
$.ajax({
url: "/property_bldg.php",
dataType: "jsonp",
data: {
query: request.term
},
success: function( data ) {
response( $.map( data.suggestions, function( item ) {
return {
label: item.text,
value: item.text
}
}));
}
});
},
minLength: 1
})
Return
{query:'A',par1:'',suggestions:['AUSTIN RD','ARCH','ARGYLE ST','AMOY GDN','ARIA','AQUAMARINE','ACADEMIC TERR','APEX','ALLWAY GDN','AP LEI CHAU DRIVE'],data:[]}
Updated:
$('#autocomplete_propSearch').autocomplete({
source: function( request, response ) {
$.ajax({
url: "/property_bldg.php",
dataType: "json",
data: {
query: request.term
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert('Error')
}
else {
response( $.map( xhr.responseText.suggestions, function( item ) {
return {
label: item,
value: item
}
}));
}
}
});
},
minLength: 1
})
You’re iterating over an array of strings, but trying to access the
textproperty of them. Change your map body to:Working example at jsFiddle. If that doesn’t work for you, check whether the ajax call really completed successfully (by printing
datato console, for instance).Update: if your server is returning exactly what you posted, then it’s not a valid JSONP response. See this tutorial and the jQuery docs for the proper way of doing JSONP (though, if you’re querying the same domain that served the page, it’s simpler – and safer – to use
jsoninstead).For instance, if your server is receiving the query:
The correct response should be:
And its
content-typeshould betext/javascript(notapplication/json). You can customize that if you want, read the docs for more info.