0

I am calling an HTTP POST Request, the response is JSON data.

POST Request:

const postXHR = new XMLHttpRequest();
postXHR.open('POST', postOptions);
postXHR.setRequestHeader("Accept", "text/json");
postXHR.setRequestHeader("Content-Type", "text/json");
postXHR.onreadystatechange = function() {
    const response = postXHR.response;
    if (response.response) {
        console.log(postXHR.status);
    }
    createNewOptionValues(response);
}
postXHR.send('{"optionName":"optionName46", "platformName":"platformName46","dotDigitalId":3,"googleId":4}');

POST Response/JSON Data:

{
    "data": {
        "rooftopGoogleOptionId": 99,
        "googleId": 4,
        "dotDigitalId": 3,
        "optionName": "optionName46",
        "optionValue": null,
        "platformName": "platformName46",
        "googleAccount": null,
        "dotDigitalAccount": null,
        "updatedBy": null,
        "updatedAt": null,
        "createdBy": "root",
    },
    "status": 201,
    "message": "success"
}

The createNewOptionValue function should log the value of a property within the response.

function createNewOptionValues(obj){
    console.log(obj.googleId);
    console.log(obj['googleId']);
}

Yet, the output is undefined, when using console.log(obj), the response does show.

5
  • You need to call JSON.parse() to conver the JSON to an object. Commented Aug 18, 2021 at 4:57
  • It was throwing error "unexpected end of json input" until I added .data after obj and before .googleId Commented Aug 18, 2021 at 5:03
  • Neither of those should affect whether JSON.parse() works. Commented Aug 18, 2021 at 5:05
  • I understand what you're saying, I'm just letting you know simply adding JSON.parse(obj.googleId) to the code, did not solve the issue, instead an error was thrown, the error went away when .data was included as JSON.parse(obj.data.googleId); Commented Aug 18, 2021 at 5:09
  • It should be JSON.parse(obj). Commented Aug 18, 2021 at 5:33

1 Answer 1

1

When you receive a response, it is in "text" format (in most of the cases) So you need to pass that response to JSON.parse for accessing it as a JSON Object.

Adding just 1 line in your createNewOptionValues function will make it work. Also, you need to access obj.data.googleId instead of accessing obj.googleId

function createNewOptionValues(obj){
    obj = JSON.parse(obj)
    console.log(obj.data.googleId);
    console.log(obj.data['googleId']);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.