I have this code:
My mysql table 'countries' contains the columns: id and name
<input type="text" name="country" id="country" class="form-control input-lg" autocomplete="off" placeholder="Type Country Name" />
<input type="hide" name="id_country" id="id_country" />
<script>
$(document).ready(function(){
$('#country').typeahead({
source: function(query, result)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
<?php
//fetch.php
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM countries WHERE name LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["name"];
}
echo json_encode($data);
}
?>
The above code is a demo, the full version is here
How can I import the country id and insert it into the id_country input?
Thank you!
You can do everything in the same query
$query = "INSERT INTO table (country_id) SELECT id FROM table";
just change the table value
Try adding a change listener and use it to assign the ID when a change fires on the typeahead input element.
$('#country').change(function(ev){
var id = ($(this).typeahead("getActive") || {}).id;
$('#id_country').val(id);
});
PS: You also have to change
$data[] = $row["name"];
to
$data[] = $row;
so that the ID is also part of the JSON encoded data which then should look like:
[{ "id": 1, "name": "Australia"}, { "id": 2, "name": "Germany"}]
Try this one
$('#id_country').val(<country-code>);
For this you have to return both country name and id from PHP. When user selects the country you can trigger the click event to insert the selected country id value into input.