Question

When i print this: console.log( response );

It gives me this json array:

{    
    "myStudentId":17,
    "myName":"beng",
    "myAge":38,
    "myAddress":"Los Angeles, California, USA.",
    "myGender":"Female",
    "myReligion":"Catholic",
    "myStatus":"boom",
    "myOccupation":"Actress",
    "myEducationLevel":"Undefined",
    "graduate":true
}

I want to access the graduate value. What I tried so far is:

console.log( response["graduate"] );
console.log( response.graduate );

But this all returns undefined. Is there a way to do this? If possible I don't want to use loop. I want to access it through key if only possible.

EDIT:

I'm using x-editable success method for the call back.

$(this).editable({
    pk: pk,
    name: id,
    url: '../admin/edit_studentInfo.do',
    validate: function( value ) {
       if($.trim( value ) == '') {
          return 'This field is required';
       } else if( isNaN( value ) && id == 'age' ) {
          return 'Only accepts numbers';
       }
        },
    success: function(response, newValue) { // call back
       var test = response;
       console.log( JSON.stringify(response) );
       console.log( response );
       console.log( response["graduate"] );
       console.log( response["myName"] + ', ' + response.myName );
    }
});

I included my editable initialization and also the test

Was it helpful?

Solution

response is a string. You need to parse it as JSON before you can access any of the properties of the encoded object:

response = JSON.parse(response);
console.log(response.graduate);

Alternately, tell use $.getJSON or pass dataType : "JSON" and jQuery will do the parsing for you.

OTHER TIPS

Add a ajaxOption

ajaxOptions: {
dataType: 'json'
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top