i’m struggling with jQuery autocomplete whole day. I cannot figure out how to connect jQuery UI autocomplete with mysql database. I don’t know what should php file look like, how’s request sent to php etc.. In demos and documentation on jQuery site there is simple example with remote datasource where source is: source: “search.php”. So how search.php knows what i’ve typed in input box? there is no query attached to search.php :/ I’ve noticed that json is used.. i’m confused and i’ve tried dozen method without results. What i need is simple autocomplete with name of cities that contains text i’ve typed into textbox.
My db looks like:
table_cities:
-------------
id: -city id
name: -city name
And i need autocomplete to show me cities that contains text i’ve typed into textbox e.g.
“po” will result in “liverpool” “Portsmouth”…
html
----
<input type="text" id="cities" />
js
--
$( "#cities" ).autocomplete({
...
Thanks!
You just need to return a JSON-encoded array of id/value objects. The autocomplete plugin also sends over a get parameter named “q” which contains what is currently in the input box. A simple example of a
search.phpfile that would work:You’ll need to adapt that to whatever PHP framework you might be using, but the pattern should be the same – loop through the results creating an array of ‘id’ and ‘value’ objects, then json encoding that.
Edit: you might want to update the SQL to do lowercase compare (so capitalization is ignored) and other such enhancements, but this should at least get you going in the right direction.