Reputation: 89
I have the following JSON data from my API
[{"email":"[email protected]","status":"Active"}]
This is the JS/jQuery code I am using to get the data
function formLogin() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var dataString = "email=" + email + "&password=" + password;
jQuery.ajax({
url: "http://localhost/OnlineShop/API/fetch_user_login_api.php",
data: dataString,
type: "POST",
success: function(data) {
$("#login-form").html(data);
console.log('success');
//window.location.href = "store.html?shopper=";
var obj = jQuery.parseJSON(data);
alert(obj.email);
},
error: function() {
console.log('error');
}
});
return true;
}
alert(obj.email)
is throwing undefined. How do I retrieve the email and status from the JSON result?
Upvotes: 1
Views: 70
Reputation: 1454
Your "data" variable is already an object or an array, you don't need to call parseJSON.
Then, it seems that your object is an Array of objects This should work:
alert(data[0].email);
I advice you to check if your array is empty or not before calling this line.
Upvotes: 2
Reputation: 54
if you call your api and get the result like this:
[{"email":"[email protected]","status":"Active"}]
it's an array, what you can do to fix the error is:
1) change your api response structure to JSON not array
2) use for to iterate your response
And I advice you next time, you have this kind of error, just console.log the raw data to find what's the structure of it, and you'll have the solution.
Upvotes: 0
Reputation: 888
The API returns [{"email":"[email protected]","status":"Active"}]
as it is of type Array.
first you need to take the first element of the Array by obj = obj[0]
.
then it is something like {"email":"[email protected]","status":"Active"}
.
now you can get the email element by simply obj["email"]
Upvotes: 0