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
?
This question is related to
jquery
ajax
json
asp.net-mvc-3
I think you should mention dataType: 'json'
in ajax config and to access that value:
data[0].name
If you response is like {'customer':{'first_name':'John','last_name':'Cena'}}
var d = JSON.parse(response);
alert(d.customer.first_name); // contains "John"
Thanks,
Try this code..
function (data) {
var json = jQuery.parseJSON(data);
alert( json.name );
}
Here is a friendly piece of advice. Use something like Chrome Developer Tools or Firebug for Firefox to inspect your Ajax calls and results.
You may also want to invest some time in understanding a helper library like Underscore, which complements jQuery and gives you 60+ useful functions for manipulating data objects with JavaScript.
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)
You might want to try this approach:
var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);
console.log(jsonData[0].name)
You should do
alert(data[0].name); //Take the property name of the first array
and not
alert(data.myName)
jQuery should be able to sniff the dataType for you even if you don't set it so no need for JSON.parse.
fiddle here
Source: Stackoverflow.com