javascriptphpxmlhttprequestsmarty3

XMLHttpRequest.responseText is not rendering the json encoded output


My $request->generate( 'web_notifier' ) generated link:

header( 'Content-Type: application/json' );

# Die is used to ensure nothing else is being outputted further down the script

die( json_encode ( array(
    'session' => array(
        'token' => $request->session( 'crsf_token' )
    )
) ) );

When I visit this API link, I get this output (and I can see that the Content-Type in the header is set to application/json:

{"session":{"token":"3d096c30a00da9ab37019122622dac80edec6db0cf006d5f4450ecd8d813c692"}}

However, if I now try to use a XMLHttpRequest to view the session.token, like below, I get Cannot read property 'token' of undefined which tells me that it has not been rendered as JSON.

let req = new XMLHttpRequest();
req.onload = () => {
    console.log(req.responseText.session.token);
    console.log(req.responseText['session']['token']);
};
req.open( 'GET', '{{$request->generate( 'web_notifier' )}}' );
req.send();

I did a console.log(req.responseText) and can see that it is in String format - Why is this if I have specified the Content-Type correctly and used json_encode() ? How can I fix this?


Solution

  • The json parsing is not automatic you need to passe your response into JSON.parse(str), also i advise you to use fetch instead of XMLHttpRequest it has a builin conversion.

    fetch(url).then(res => res.json()).then(handler)
    

    jsonString = '{"data": "some_data"}'
    console.log(JSON.parse(jsonString))