I\'m trying to create an auto-complete function into a textbox but the result should come from my SQL database.
Here\'s the code that i\'m trying to configure:
<
The jQuery UI autocomplete can take 3 different types of values of the source option:
term parameter in a query-string appended to the URL we provided.Your original code uses the first, an array.
var availableTags = [
"autocomplete.php";
];
What that tells the autocomplete is that the string "autocomplete.php" is the only thing in the list of things to autocomplete with.
I think what you were trying to do is embed it with something like this:
$(function() {
var availableTags = [
;
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
That would probably work okay assuming that the list of things that are being returned from the database will always remain short. Doing it this way is kind of fragile though since you are just shoving raw output from PHP into your JS. If the returned data contains " you might have to use addSlashes to escape it correctly. You should however change the query to return a single field rather than *, you probably only want one field as the label in the autocomplete not the entire row.
A better approach, especially if the list could potentially grow very large, would be to use the second method:
$(function() {
var availableTags = "autocomplete.php";
$( "#tags" ).autocomplete({
source: availableTags
});
});
This will require you to make a change to the back-end script that is grabbing the list so that it does the filtering. This example uses a prepared statement to ensure the user provided data in $term doesn't open you up to SQL injection:
It's been a while since I've worked with mysqli, so that code might need some tweaking as it hasn't been tested.
It would be good to get into the habit of using prepared statements since when properly used, they make SQL injection impossible. You can instead use a normal non-prepared statement, escaping every user-provided item with mysqli_real_escape_string before you insert it into your SQL statement. However, doing this is very error-prone. It only takes forgetting to escape one thing to open yourself up to attacks. Most of the major "hacks" in recent history are due to sloppy coding introducing SQL injection vulnerabilities.
If you really want to stick with the non-prepared statement, the code would look something like this: