function (data) { //add values based on activity type //data = JSON.parse(data); //alert(abc.Phone1); alert(data.myName) alert(data.toString()); if (activityType == "Phone") { } return; },
As you can see this callback function of $.ajax
taking JSON
data from controller.
For example:
[{"name":"myName" ,"address": "myAddress" }]
In this case my first alert giving me undefined and second/third alert popup comes up with:
[{"name":"myName" ,"address": "myAddress" }]
How can I access value by name so that my first alert filled out with myName
which is value of name
?
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
You simply use a dot like so: obj.StudentData.Name . This is of course assuming as Kevin B says below, that you've used JSON. parse and that it's valid json (the stuff you posted is not valid json - you're missing starting brackets and DateOfBirth isn't a string).
JSON names are on the left side of the colon. They need to be wrapped in double quotation marks, as in “name” and can be any valid string. Within each object, keys need to be unique. JSON values are found to the right of the colon.
In stead of parsing JSON you can do like followng:
$.ajax({ .. dataType: 'json' // using json, jquery will make parse for you });
To access a property of your JSON do following:
data[0].name; data[0].address;
Why you need data[0]
because data is an array, so to its content retrieve you need data[0]
(first element), which gives you an object {"name":"myName" ,"address": "myAddress" }
.
And to access property of an object rule is:
Object.property
or sometimes
Object["property"] // in some case
So you need
data[0].name
and so on to get what you want.
set dataType: json
then you need to parse them using $.parseJSON()
and to retrieve data like above.
The JSON you are receiving is in string. You have to convert it into JSON object You have commented the most important line of code
data = JSON.parse(data);
Or if you are using jQuery
data = $.parseJSON(data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With