5

I have the code below which i am passing through json to jquery.

$string['msg']['1']['Name'] = "John Doe";
$string['msg']['1']['Said'] = "Hello there";

$string['msg']['2']['Name'] = "Jane King";
$string['msg']['2']['Said'] = "Hello there";

$string['errors']['1']['Person'] = "Jane King";
$string['errors']['1']['type'] = "Wrong Screwdriver";


$string['errors']['2']['Person'] = "John Doe";
$string['errors']['2']['type'] = "Wrong Spanner";

The JSON output is below:

{"msg":{"1":{"Name":"John Doe","Said":"Hello there"},"2":{"Name":"Jane King","Said":"Hello there"}},"errors":{"1":{"Person":"Jane King","type":"Wrong Screwdriver"},"2":{"Person":"John Doe","type":"Wrong Spanner"}}}

This is the ajax code that is retreiving the json.

$.ajax({
    dataType : 'json',
    url: 'polling.php',
    type: 'post',
    data: 'id=1',
    success: function(data) {
        //read json     

});

I am trying to read all 'msg' in order of number.. 1, 2.. and get 'Name' and 'Said' values for each.

Then do the same for 'errors'

but i cant correctly retrieve any values

Smile
  • 2,770
  • 4
  • 35
  • 57
sam fisher
  • 101
  • 1
  • 2
  • 4

2 Answers2

5

As per your given output:

Try this:

$(function(){

    var  data = {"msg":{"1":{"Name":"John Doe","Said":"Hello there"},"2":{"Name":"Jane King","Said":"Hello there"}},"errors":{"1":{"Person":"Jane King","type":"Wrong Screwdriver"},"2":{"Person":"John Doe","type":"Wrong Spanner"}}};

    $.each(data.msg, function(index, value) {
      alert(index + ': ' + value.Name);
    });

});

JSFiddle Example

Satpal
  • 132,252
  • 13
  • 159
  • 168
3

Demo Link

var data = {"msg":{"1":{"Name":"John Doe","Said":"Hello there"},"2":{"Name":"Jane King","Said":"Hello there"}},"errors":{"1":{"Person":"Jane King","type":"Wrong Screwdriver"},"2":{"Person":"John Doe","type":"Wrong Spanner"}}};


$.each(data['msg'], function(key, element){
    console.log(key+' : '+element['Name']);
});

$.each(data['errors'], function(key, element){
    console.log(key+' : '+element['Person']);
});
Jayendra
  • 52,349
  • 4
  • 80
  • 90