I have a <input>
that displays suggestions when someone types in it. I am building the backend to it so that ajax grabs the first five tags in the database that have that letter sequence and displays it in spans in particular <div>
. I don't seem to be completely succeeding. This is the first Ajax I have ever done. Help would be greatly appreciated. Below is the applicable HTML, Javascript, and PHP. I think I am close but not exactly sure how to continue. The problem is probably in the javascript.
HTML:
<label id="testTagsLabel">Tags:</label>
<input type="text" name="tags" id="testTags" placeholder="Ex: Poem, Edgar Allen Poe">
<div id="tagSuggest">
<ul>
<!--the javascript would add the suggests as list items here-->
</ul>
</div>
PHP:
<?php #create_set.ajax.php
$tagSuggestions = array();
$currentTag = $_POST['sendTag'];
if (!empty($currentTag)){
require_once (MYSQL); //gets the database connection
$enteredTag = mysqli_real_escape_string ($dbc, $currentTag);
$q = "SELECT name FROM tags WHERE MATCH(name) AGAINST('$enteredTag'.'*' IN BOOLEAN MODE) LIMIT 5";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) > 0) {//if there are tags that match what the user typed
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$tag = $row['name'];
$tagSuggestions[] = $tag;
}
echo json_encode($tagSuggestions);
}
}
?>
Javascript:
$(function(){
function sendTag(str){
$.post("../includes/create_set.ajax.php",{ sendTag: str },
function(data){
for (var key in data.returnTag) {
if(data.returnTag.hasOwnProperty(key)) {
$('#tagSuggestTag').html('<li class="tagSuggestTag">' + data.returnTag + "<li>");
}
}
}, "json");
}
$('#testTags').keyup(//on key press in tag field show the send the request and show the suggestions
function(){
sendTag($(this).val());
$('#tagSuggest').show();
});
});