Tags Input with Autocomplete with jQuery using PHP


Tags are used to arrange articles or posts on the website. Tags give an efficient way to group related articel or posts and make it improved for the user to find the appropriate posts rapidly. It also helps user to get a summary idea about the post without reading the whole content. Tags are more like categories, but they can explain articel or posts in more detail than categories. Usually, one category is allocated to a post or article, on other way you can use multiple tags for a single article or post.

The tags input field must be allowed to input multiple values divided by a specific separator. Mainly, the comma (,) is used as a separator for the multiple value input. In this article, we will show you how to generate multiple tags input field using jQuery. You can make a user view to manage tags with autocomplete aspect with jQuery and PHP.

The given code will merge a text field to input multiple tags. Also, an autocomplete attribute will be provided to show tag recommendation from the DB under the input field while the user starts word typing.

Also Read:

Tags Input with jQuery

In this given code sample, we will use the TagsInput jQuery plugin to change a plain text input field to the tag list input area and permit the user to input multiple tag values.

  • The tag can be added by entry a comma (,).
  • The tag can be removed by a crossing icon (x).

Define an HTML input field.

<input type="text" id="tags_input">

Include the jQuery and TagsInput library files to html.

<!-- Include jQuery library -->
<script src="js/jquery.min.js"></script>

<!-- Include TagsInput jQuery library -->
<script src="js/jquery.tagsinput.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.tagsinput.css" />

Initialize the tagsInput plugin and define the selector (#tags_input) to bind it to the input field.


Tags Input with Autocomplete using PHP and MySQL DB

In the given example code snippet, we will show you to add autocomplete option to the tags input field with using jQuery and PHP.

Create DB Table:

To save the autosuggestion tags data in table is required in the DB. The Given SQL generates a tags DB table with some simple fields in the MySQL database.

  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

HTML Input Element:
Create an input element with HTML.

<input type="text" id="tags_input">

Include jQuery Library:
jQuery library is needed to use the TagsInput plugin.

<script src="js/jquery.min.js"></script>

jQuery UI Library:
To use autocomplete option in tagsInput, the jQuery UI library is needed. add the jQuery UI library files first.

<link rel="stylesheet" href="js/jquery-ui/jquery-ui.min.css">
<script src="js/jquery-ui/jquery-ui.min.js"></script>

tagsInput Plugin:
Add the library files of the tagsInput jQuery plugin.

<script src="js/jquery.tagsinput.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.tagsinput.css" />

Fixed server-side script URL in autocomplete_url feature of the tagsInput() method.

    'autocomplete_url': 'fetchData.php',

Retrieve Autocomplete Tags from DB using PHP and MySQL (fetchData.php):

The fetchData.php file is named by the tagsInput() method to fetch the tags from the server-side script developed on the search term.

  • Get the search term using the PHP $_GET method.
  • Retrieve the matching records from the database with PHP and MySQL.
  • Return tags data as JSON encoded array using PHP json_encode() function.
// Database configuration 
$dbHost     = "localhost"; 
$dbUsername = "root"; 
$dbPassword = "root"; 
$dbName     = "codexworld"; 
// Create database connection 
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
// Check connection 
if ($db->connect_error) { 
    die("Connection failed: " . $db->connect_error); 
// Get search term 
$searchTerm = $_GET['term']; 
// Fetch matched data from the database 
$query = $db->query("SELECT * FROM tags WHERE name LIKE '%".$searchTerm."%' AND status = 1 ORDER BY name ASC"); 
// Generate array with tags data 
$tagsData = array(); 
if($query->num_rows > 0){ 
    while($row = $query->fetch_assoc()){ 
        $data['id'] = $row['id']; 
        $data['value'] = $row['name']; 
        array_push($tagsData, $data); 
// Return results as json encoded array 
echo json_encode($tagsData); 

tagsInput Options

Several configuration choices are accessible to customize the tagsInput() functionality. Some helpful options are given.

  • autocomplete_url – URL to fetch the autocomplete data
  • autocomplete – Options and values for autocomplete data ({option: value, option: value})
  • height – Set the height of the tags input area (100px)
  • width – Set width of tags input area (300px)
  • delimiter – Separator for a new tag ([‘,’,’;’] or a string with a single delimiter. Ex: ‘;’)
  • removeWithBackspace – Remove tag by backspace (true)
  • minChars – Set the Mini  character limit (default, 0)
  • maxChars – Set the max character limit (default, no limit)
  • placeholderColor – Placeholder text color (default, #666666)

Get Value of Input Tags with PHP

When the form is submitted, you can fetch the value of the tags input field using the $_POST method using PHP. The given example code shows how to submit the form and get the tags input field’s value with PHP.

HTML Form with Tags Input:

<form method="post" action="submit.php">
    <!-- Input field -->
    <div class="form-group">
        <input type="text" id="tags_input" name="tags_input">

    <!-- Submit button -->
    <input type="submit" name="submit" value="Submit">

Get Value of Tags Input:
Next the form submit, use the $_POST method in PHP to fetch the value from the tags input field.

    $tags = $_POST['tags_input']; 
    echo '<p><b>Selected Tags:</b></p> '.str_replace(',', '<br/>', $tags); 

Related Post

Like it? Share with your friends!