Search code examples
jqueryasp.netajaxjsonresponse

How do i access json response object fields


I am trying constructing a table after my response and attemtpting to append response data to the table. My response comes back correctly as shown below

Object {__type: "DomainLayer.BusinessLogic.UserOnlineCommunity", CommunityID: "15bb29d4-b451-4034-be7e-8197723e0a89", Description: "name", Detail: "yes", Link: "test"}

but i am trying to access the the fields such as Description, or Details, but when i debug and log those fields into the console as i am doing in the code below, i get undefined. how do i get the value of each field.

function UpdateOnlineCommunity(communityId, communityName, communityDescription, communityLink) {
var serviceData = JSON.stringify({
    'communityId': communityId,
    'communityName': communityName,
    'communityDescription': communityDescription,
    'communityLink': communityLink
});
$.ajax({
    type: "POST",
    url: "PresentationService.asmx/UpdateUserCommunity",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: serviceData,
    success: function (response) {
        var data = response.d;
        console.log(data);
        $.each(data, function () {
            var tblCommunity = $('#tblCommunity');
            console.log(this['Description']);
            var rowDescription = $('</tr></tr>');
            rowDescription.append('<td>' + this['Description'] + '</td>');

            var rowDetail = $('</tr></tr>');
            rowDetail.append('<td>' + this['Detail'] + '</td>');

            var rowLink = $('</tr></tr>');
            rowLink.append('<td>' + this['Link'] + '</td>');

            var rowUpdateBtn = $('</tr></tr>');
            rowUpdateBtn.append('<button>Update</button>');

            tblCommunity.append(rowDescription);
            tblCommunity.append(rowDetail);
            tblCommunity.append(rowLink);
        });
    },
    error: function (response) {
        alert(response);
    }
});

Solution

  • Your response is a single object, so the use of each is causing problems. You can simply access the properties of the object by using data.Description for example. Try this:

    success: function (response) {
        var data = response.d;
        var tblCommunity = $('#tblCommunity');
        var rowDescription = $('<tr />').append('<td>' + data.Description + '</td>');
        var rowDetail = $('<tr />').append('<td>' + data.Detail + '</td>');
        var rowLink = $('<tr />').append('<td>' + data.Link + '</td>');
        var rowUpdateBtn = $('<tr />').append('<button>Update</button>');
        tblCommunity.append(rowDescription, rowDetail, rowLink);
    },
    

    Example fiddle

    Also note that the syntax you were using to create your elements - </tr></tr> was incorrect.