Every time I execute the javascript/php code below, I encounter an issue where I keep receiving "undefined" when trying to alert the 'userid' property of the json object. However, if I turn the json object into a string using stringify(), it correctly returns "[{'userid':'1'}]".
Why am I facing this problem when attempting to access the correct field of the json object?
Below is the ajax script I am utilizing to retrieve the object:
$.ajax({
type: 'POST',
url: 'WebPHP/check_login.php',
contentType: "application/json; charset=utf-8",
data: finalObject,
async: false,
dataType: 'json',
success: function(data) {
if (data["result"] === false) {
alert("Invalid Email or Password");
} else {
var userID = data["result"];
alert(userID["userid"]);
var url = "AMessage.html";
alert(JSON.stringify(data["result"]));
}
}
});
And here is the php code that interacts with the database:
$json = file_get_contents('php://input');
$jsondata = json_decode($json);
$email = $jsondata - > email;
$password = $jsondata - > password;
$sql1 = " SELECT user_id as userid
FROM users
WHERE email = '$email'
AND password = '$password';
";
$result = mysqli_query($Thesisdb, $sql1) or die(mysqli_error($Thesisdb));
$rows = $result - > num_rows;
while ($row = $result - > fetch_assoc()) {
$response[] = $row;
}
$post_data = array();
if ($rows == 1) {
$post_data = array('result' => $response);
} else {
$post_data = array('result' => false);
}
echo json_encode($post_data);
mysqli_close($Thesisdb);