Reputation: 13448
I have the following code and i am trying to retrieve the userid , firstname and some values from JSON but I am getting undefined.
How can i fix this?
function getVal(val1,val2) {
var myval2 =URL +"webUser?email="+email;
var uId='';
$.ajax({
url: myval2,
dataType: "json",
cache: false,
success: function(data, textStatus, jqXHR) {
jQuery.each(data, function(k,v) {
console.log( " k " +k + " v" + v);
uId =v.uId;
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('FAILED to get JSON from AJAX call' + jqXHR + textStatus + errorThrown);
}
});
console.log("userid " +userId);
return userId;
}
JSON
{
"userId": 2,
"emailAddress": "[email protected]",
"roleId": 1,
"firstName": "Hulk",
"lastName": "Ogan",
"company": "MTT",
"title": "Lord Vader",
"phoneWork": "",
"phoneMobile": "",
"lastModifiedBy": "system",
"versionNumber": 1
}
Upvotes: 0
Views: 55
Reputation: 32354
You can simply get value of userid and other properties like this
userID = data['userId'];
var data = {
"userId": 2,
"emailAddress": "[email protected]",
"roleId": 1,
"firstName": "Hulk",
"lastName": "Ogan",
"company": "MTT",
"title": "Lord Vader",
"phoneWork": "",
"phoneMobile": "",
"lastModifiedBy": "system",
"versionNumber": 1
};
console.log(data['userId']);
Upvotes: 0
Reputation: 593
You don't need to jQuery.each, because you don't have a JsonArray and you have JsonObject. You can easily get you data with:
userID = data.userId;
and
userID = data['userId'];
(like as Madalin & Leopars answers)
Upvotes: 0
Reputation: 14604
You can simply get value of userid and other properties like this
userID = data.userId;
No need of loop because your data
is only a single object
you will need loop
if your data
was an array of objects
Upvotes: 2
Reputation: 120
One problem I can see is that your json record is just that: a single record; so, you don't need $.each to iterate through the ajax result - that would only be necessary if your returned data consisted of a json array with potentially many records.
Other than that, you will just need to do some bug tracking:
Upvotes: 0