I try to make a multiple autocomplete input that can save token in itself. Options should come from database in this case MySql and php; Demo example project.
This demo uses Tokenfield for Bootstrap, jQuery and ajax.
However, I get an error:
VM11207:1 Uncaught SyntaxError: Unexpected token '<', "<br />
<b>"... is not valid JSON
at JSON.parse (<anonymous>)
One option is to fetch data as array from backend and use it in javascript. But I don't how to do it.
index.php
<!DOCTYPE html>
<html>
<head>
<title>AutoComplete Textbox with Multiple Field using jQuery in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tokenfield/0.12.0/css/bootstrap-tokenfield.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tokenfield/0.12.0/bootstrap-tokenfield.js"></script>
</head>
<body>
<br />
<br />
<div class="container">
<h1 align="center">AutoComplete Textbox with Multiple Field using jQuery in PHP</h1>
<br />
<br />
<br />
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8">
<div class="form-group">
<label>Enter Multiple Country Name</label>
<div class="input-group">
<input type="text" id="search_data" placeholder="" autocomplete="off" class="form-control input-lg" />
<div class="input-group-btn">
<button type="button" class="btn btn-primary btn-lg" id="search">Get Value</button>
</div>
</div>
<br />
<span id="country_name"></span>
</div>
</div>
<div class="col-md-2">
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#search_data').tokenfield({
autocomplete :{
source: function(request, response)
{
jQuery.get('fetch.php', {
query : request.term
}, function(data){
data = JSON.parse(data);
response(data);
});
},
delay: 100
}
});
$('#search').click(function(){
$('#country_name').text($('#search_data').val());
});
});
</script>
fetch.php:
<?php
//fetch.php;
$data = array();
if(isset($_GET["query"]))
{
$connect = new PDO("mysql:host=localhost; dbName=testing ", "username", "passwor");
$query = "
SELECT country_name FROM apps_countries
WHERE country_name LIKE '".$_GET["query"]."%'
ORDER BY country_name ASC
LIMIT 15
";
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row["country_name"];
}
}
echo json_encode($data);
?>