Reputation: 60
I'm trying to check an user input in a html form to a list of allowable values in a database using Ajax and then I want to display the corresponding message. This is the code I'm using:
js
$(document).ready(function(e){
$.ajax({
type: 'POST',
url: 'datafile.php',
dataType : "json",
success: function(result) {
$("#postal_code").change(function(){
var postal_code = $("#postal_code").val().slice(0,-2);
if ($.inArray(postal_code,result) !== -1){
console.log('success');
} else {
console.log('failure');
}
});
}
});
});
datafile.php
<?php
require_once("./db_con.php");
$query = mysqli_query($con, "SELECT postal_code FROM table");
$rows = mysqli_fetch_all($query);
echo json_encode($rows);
mysqli_free_result($query);
mysqli_close($con);
exit();
?>
The problem I'm having is the input value never matches any of the values in the result
variable even through I know that they are in the database. I think the issue is related to the fact that the result
variable contains arrays in side another array, e.g. [["value1"],["value2"],["value3"]]
.
Upvotes: 1
Views: 68
Reputation: 78994
I can't really speak to the JavaScript portion, but since you are only selecting one column you can extract it into a single dimension. mysqli_fetch_all
fetches a numerically indexed array by default:
$rows = array_column(mysqli_fetch_all($query), 0);
Or fetch and extract by column name:
$rows = array_column(mysqli_fetch_all($query, MYSQLI_ASSOC), 'postal_code');
Upvotes: 1