PHP to javascript JSON.Parse twice

Viewed 23

I have this in PHP

$invalid_code_msg = ['error' => 'Invalid purchase code. Please double check your purchase code and try again!'];
throw new Exception(json_encode($invalid_code_msg));

In js:

var xhr = new XMLHttpRequest;
xhr.onerror = function (e) {
    console.error(xhr.statusText);

};
xhr.onreadystatechange = function () {

    if (this.readyState === 4){

        if (this.status === 200) { 

            var data = JSON.parse(xhr.responseText);
            console.log(data, data.error)

            //here data is still a string unless I parse it twice?
        }
    }

};


xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("pc=" + purchase_code.value);

I am trying to figure out why data is still a string unless I parse it twice?

data is still a string after first JSON.parse 

{"error":"Invalid purchase code. Please double check your purchase code and try again!"}
0 Answers
Related