0

Here is the json returning from controller through ajax

[{"UserID":"1","Username":"admin","Password":"#######","FullName":"Hassan","Email":"admin@admin.com","Phone":null,"Mobile":null,"PreviousAddress":null,"CNIC":null,"theme":null,"GroupID":"1"}]

i want to get values from the array.

I tried like this

success: function(data){
    console.log(data.UserID);
}

but i get undefined in the console.

Sizzling Code
  • 5,932
  • 18
  • 81
  • 138
  • 1
    `data` is an array. Elements should be accessed as `data[i].UserId`, and so on. Also, make sure you are sending `content-type: text/json` header along with the response! – Haywire Oct 04 '14 at 14:26
  • You should mention that you are using $.getJSON (if you do) – Endless Oct 04 '14 at 14:27
  • @DOCASAREL: looks pretty much like JSON to me. – Felix Kling Oct 04 '14 at 14:41
  • The console says it is an object %)P @FelixKling – loveNoHate Oct 04 '14 at 14:42
  • @DOCASAREL: Sure, if you evaluate the text `[{"UserID":"1", ...}]` in a JavaScript context (like the console), it will evaluate to an array containing an object. That's no surprise since the JSON syntax is a subset of JavaScript's object literal syntax. However, if `[{"UserID":"1", ...}]` is the whole response from the server, then yes, it is JSON. – Felix Kling Oct 04 '14 at 20:36
  • Exactly that's where I am flipping right now @FelixKling. – loveNoHate Oct 05 '14 at 02:28

3 Answers3

4

You need to access the first index of the array

console.log(data[0].UserID);
meda
  • 45,103
  • 14
  • 92
  • 122
0

Set dataType to json in ajax call. The result will be parsed and returned as an object in your success result.

$.ajax({
  url: "yourscript.php",
  type: "POST",
  data: your data,
  dataType: "json"
}).
success(function (data) {
...
});
Barry
  • 3,683
  • 1
  • 18
  • 25
0

In Javascript [] means array therefore your Object it is actually an array of objects [{"UserID":"1",...},{"UserID":"2",...}, etc]

In order to access each object you will need to loop trough or use the index number you want to access like var obj =[{"UserID":"1",... then obj[0].UserID

Dalorzo
  • 19,834
  • 7
  • 55
  • 102