I have a input box where the user enters in a zip code. I created an auto-suggest function that recommends zip codes based on the ones i have store in my database. Right now I linked it so the actual value of the zip code rather than the primary key. I am not sure how I can pass my primary key into my PHP file rather than the actual value.
HTML:
<div class="label">Zip Code:</div><br>
<input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Please enter your Zip Code" onkeyup = "autocomplete()">
<ul id = "zip_codes_list_id"></ul>
JS:
function autocomplete()
{
var min_length = 1;
var keyword = $('#zip_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#zip_codes_list_id').show();
$('#zip_codes_list_id').html(data);
}
});
} else {
$('#zip_codes_list_id').hide();
}
}
function set_item(item)
{
// change input value
$('#zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
PHP:
<?php
//connect to db here
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs)
{
// put in bold the written text
$zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>';
}
?>
From here I could do a POST request in my php file and i would store the actual zip code that the user entered. I however want to store the primary key associated with that zip code.