woopata
woopata

Reputation: 875

jQuery UI autocomplete with mysql database

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!

Upvotes: 0

Views: 5317

Answers (3)

Emin Net Bilişim
Emin Net Bilişim

Reputation: 1

You can use ".=" in while loop.

$data = "";
while($row = mysqli_fetch_assoc($result))
{
$data .= "bla bla bla..."
}

Upvotes: -1

Parrots
Parrots

Reputation: 26882

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.php file that would work:

$autocomplete_value = mysql_real_escape_string($_GET["q"]);
$sql = "select id, name from table_cities where name LIKE '%$autocomplete_value%'";
$query = mysql_query($sql);

$results = array();
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
    array_push($results, array('id' => $row['id'], 
                               'value' => $row['name']) );
}
echo json_encode($results);

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.

Upvotes: 2

user610217
user610217

Reputation:

I haven't used jQuery autocomplete, but it seems clear that it makes an AJAX call back to your web server, providing the data that has already been typed in the box. The web server will query the database as you see fit, and return the results that should be displayed.

The query would not be part of the jQuery plugin; you would have to write that yourself.

Upvotes: 0

Related Questions