I am trying to have two autocompleted fields. The first one works, as it is the straightforward example of autocomplete. The second field's autocomplete validation includes the value of the first field as a condition in the query. I have been chasing this back and forward and I am unsure if it is Jquery or PHP where my issue lies.
HTML and Jquery
<form action='' method='post'>
<p><label>Country:</label><input type='text' id='country' name='country' value='' class='auto'></p>
<p><label>State:</label><input type='text' id='state' name='state' value='' class='auto'></p>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$("#country.auto").autocomplete({
source: "search.php",
minLength: 1,
change: function (event, ui){
if (!ui.item) {
this.value = '';
}
}
});
});
</script>
<script>
$(function(){
$("#state.auto").autocomplete({
source: "statesearch.php?country=" + $("#country.auto").val(),
minLength: 1,
change: function (event, ui){
if (!ui.item) {
this.value = '';
}
}
});
});
</script>
PHP for second field (first is working fine):
$country = $_GET['country'];
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT state FROM states WHERE state LIKE :term and country ='.$country);
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['state'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
The states table in the DB is simple, three columns, ID, country, state
Thanks in advance for any clues or steps I could go down.