I am using Jquery Autocomplete to fetch a list of tags from a mysql table. When the user picks one tag from the list, it gets saved on the page. I am trying to prevent the already saved tag from being displayed again.
Here is my code:
HTML
<input type="text" id="tag">
<input type="text" id="tags" style="display:none;">
Jquery
$('#tag').autocomplete({
source : function(request, response) {
$.ajax({
url : 'tags.php',
dataType : "json",
method : 'post',
data : {
searchQuery : request.term,
selectedTags: $('#tags').val() //sends already selected terms
},
success : function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label : code[0],
value : code[0],
data : item
}
}));
},
error: function(jqxhr, status, error)
{
alert(error);
}
});
},
autoFocus : true,
minLength : 1,
select : function(event, ui) {
var names = ui.item.data.split("|");
tag_ids = [];
tag_names = [];
tags = $('#tags').val();
if(tags != '')tag_names = tags.split(',');
tag_ids.push(names[1]);
tag_names.push("'" + names[0] + "'");
$('#tags').show();
$('#tags').val( tag_names.join( "," ) );
$('#tag').val('');
}
PHP
$searchQuery = $_POST['searchQuery'];
$selectedTags = $_POST['selectedTags'];
if(!empty($selectedTags))
{ $query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN ?");
$query->execute(array($searchQuery . "%", $selectedTags));
}
else
{
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ?");
$query->execute(array($searchQuery . "%"));
}
When I select the first suggestion, it gets saved in #tags
but then no other suggestion is displayed. If there is any other suggestion to achieving this, that'd be great.