I have an input(typeahead) where users are supposed to type in a name. Based on that name, I am using ajax to retrieve two different set of values from the database that I display in 2 dropdowns. These two fields are arrival type and sub-name.
I have added an onchange action on the input and calling the function when the user starts typing.
It does not seem to work so far. Here is my code
<input type="text" class="form-control typeahead text_field"
name="name_alias" id="name_alias" placeholder="Search unit" style="min-
width:200px;" onChange="getNameType();" required/>
function getNameType()
{
if (ajax) {
var name_alias = document.getElementById("name_alias").value;
if(name_alias) {
var param = "?name_alias=" + name_alias;
var url = "getNameType.php";
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax3;
ajax.send(null);
}
}
}
function handleAjax3()
{
if (ajax.readyState == 4) {
var arrival_type = document.getElementById('arrival_type');
if(!!ajax.responseText) {
var result = JSON.parse(ajax.responseText);
if(!!result){
$('#arrival_type').val((!!result.arrival_type) ? result.arrival_type: '');
}
}
}
}
My getNameType File
<?php
$conn = mysqli_connect("","","","");
$name_alias = mysqli_real_escape_string($conn, $_GET['name_alias']);
$query = "SELECT arrival_type
FROM table_namer
WHERE name_alias='".$name_alias."'
LIMIT 1";
$result = mysqli_query($conn, $query) or die(mysql_error());
$response = array();
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$response['arrival_type'] = ($row['arrival_type'] != '') ? $row['arrival_type'] : '';
}
}
echo json_encode($response, true);
?>