0

When I run the following javascript/php, I keep getting "undefined" when alerting the 'userid' property of the json object. However, if I stringify the json object, it returns "[{'userid':'1'}] which is the correct value.

Why am I getting undefined if I am trying to access the correct name of the json object?

Here is the ajax I am using to access 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 the php that connects to the db:

$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);
3
  • Can you show your JSON result ?? Commented Apr 21, 2016 at 1:41
  • Does JSON need to have javascript processing triggered to change the view like HTML? It left me scratching my head for a while when I just started playing with ajax, so that could be your problem. Take a look at this project: github.com/ajax-proofs/proofs Commented Apr 21, 2016 at 1:42
  • You should be doing something like this while "($rows = $result->num_rows)" to process less also. Commented Apr 21, 2016 at 1:47

2 Answers 2

1

You can't access the userid property because your userID variable contains an array - that's what the [] brackets mean in the json response: [{'userid':'1'}]. Try accessing it this way: alert(userID[0]["userid"]);.

Better yet, don't return an array, since you're checkng that $rows == 1 anyway.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, as said by #Jack you can not access userid property, your json response:[{'userid':'1'}] is in array form, so you need to go for the syntax: alert(userId[0].userid)

Comments

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.