Abhishek Mahapatra
Abhishek Mahapatra

Reputation: 41

Not able to get value from JSON object using AJAX call

I have sample code for getting json value from servlet through Ajax call. In success function I am getting response. It is showing Object : [{"userId":"dfeterter"}] in console.

But I am not able to get value of userId

$.ajax({
    url: "Registration",
    dataType: "json",
    data: {
        jsonbhvalue: bhvalue,
        jsonuid: uid,
        jsonpassword: password,
        jsonfname: fname,
        jsonlname: lname,
        jsonmobile: mobile,
        jsonemailid: emailid
    },
    success: function(variable) {
        var obj = $.parseJSON(JSON.stringify(variable));
        console.log("Object     :   " + obj);
        console.log("cval     :   " + obj.userId)
    });
});

Upvotes: 0

Views: 104

Answers (2)

Tushar
Tushar

Reputation: 87233

Thanks To @RobertoNovelo.

You have to remove $.parseJSON as you are already setting JSON by ajax configuration. dataType: "json" You need to use:

obj[0].userId

Your response is array of objects.

Upvotes: 1

RobertoNovelo
RobertoNovelo

Reputation: 3829

That is because your object is an array. You should either use obj[0] or assign the array to a variable and then use its members

objs = [{"userId":"dfeterter"}]

firstobj = objs[0]

console.log("Object     :   " + objs);
console.log("cval     :   " + objs[0].userId);
console.log("cval     :   " + firstobj.userId);

Upvotes: 0

Related Questions