user5820249
user5820249

Reputation:

AJAX call using JSON data type returns undefined

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.

Upvotes: 0

Views: 225

Answers (3)

Cœur
Cœur

Reputation: 38667

Solution by OP.

The problem resolved with:

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

I had a mistake using ":" before "code":

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

Upvotes: 0

Manjeet Barnala
Manjeet Barnala

Reputation: 2995

Change This

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

To

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

Upvotes: 1

Valery K.
Valery K.

Reputation: 147

Must be something like this:

$country = $_POST["country"];
$stmt = $db -> prepare ("SELECT * FROM country WHERE name = :country");
$stmt -> execute (array (":country" => $country));
$rows = $stmt -> fetchAll (PDO::FETCH_ASSOC);
$code = array();
foreach ($rows as $row)
{
    $code[] = $row["code"];
}
echo json_encode ($code);

or simply echo json_encode ($rows); as you use PDO::FETCH_ASSOC

Upvotes: 0

Related Questions