1

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"]].

0

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks using the array_column() on the server side solved the problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.