Lara
Lara

Reputation: 3021

Not able to read Json Response

I have made a ajax Call which is returning me Values like {"SessionId":"1","UserName":"Bond","ReferrerUrl":"http://localhost:64132/Test.html","ResponseStatus":{}} in console.Now i want to read this response one by one which i am trying to do like the below code..

$.ajax({
    type: 'POST',
    url: 'http://localhost:64132/Auth',
    data: JSON.stringify(UserDetails),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        console.log(data);
        debugger;
        $.each(data, function (idx, obj) {
            var UName = obj.UserName;
            console.log(UName);
        });
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

but in the console i am getting undefined.Please help to resolve it.Thanks..

Upvotes: 0

Views: 84

Answers (2)

guest271314
guest271314

Reputation: 1

but in the console i am getting undefined

$.each() is returning correct results idx would be UserName , or property name, obj would be property value of object

$.each({
  "SessionId": "1",
  "UserName": "Bond",
  "ReferrerUrl": "http://localhost:64132/Test.html",
  "ResponseStatus": {}
}, function(idx, obj) {
  console.log(idx, obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115262

You need to parse the response data using JSON.parse() or $.parseJSON() also there is no need for $.each()

$.ajax({
    type: 'POST',
    url: 'http://localhost:64132/Auth',
    data: JSON.stringify(UserDetails),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        data = JSON.parse(data);
        console.log(data);
        // parse json string
        debugger;
        var UName = data.UserName;
        console.log(UName);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

or you need to set response datatype in $.ajax()

$.ajax({
    type: 'POST',
    url: 'http://localhost:64132/Auth',
    data: JSON.stringify(UserDetails),
    contentType: "application/json; charset=utf-8",
    dataType : 'json',
    // setting response datatype
    success: function (data) {
        console.log(data);
        // parse json string
        debugger;
        var UName = data.UserName;
        console.log(UName);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

Update : If you want to iterate the object then you can use $.each()

$.each(data, function (idx, val) {
    console.log(idx + ' : ' + val);
});

Upvotes: 1

Related Questions