The AJAX call using the JSON data type returns undefined

advertisements

I have a jQuery function who sends an AJAX call to a PHP file to check selected value of a dropdown menu and using this value return data from DB.

jQuery (document).ready(function() {
    $("#country").change(function() {
        country = $("#country").val();
        $.ajax({
            type: "POST",
            url: "script.php",
            dataType: "json",
            data: $("#address").serialize(),
            success: function(data) {
                alert(data.code);
            },
        });
        return false;
    });
});

Not working either with :

alert(data[0].code)

PHP Code:

$country = $_POST["country"];
$stmt = $db -> prepare("SELECT * FROM country WHERE name = :country");
$stmt -> execute(array(":country" => $country));
$rows = $stmt -> fetchAll(PDO::FETCH_ASSOC);

foreach ($rows as $row)
{
    $code = $row["code"];
}

echo json_encode($code);

Not working either with :

echo json_encode(array(":code" => $code));

The PHP script works fine as it return true value. Also when I check the Mozilla console the AJAX call sends the request to the PHP script correctly and it gets a return value too, but I still get undefined using alert.


Change This

foreach ($rows as $row)
{
    $code = $row["code"];
}

To

$code = array();
foreach ($rows as $row)
{
    $code[] = $row["code"];
}
echo json_encode($code);