I have a php file that generates some JSON. Then an HTML loads the JSON via JavaScript and tries to display some of the values contained in the JSON. I’m struggling with the JavaScript syntax to access the “Decision”:”Maybe” JSON data, to display “Maybe” in a paragraph.
step1.php generates the following JSON
{
"LeadResponses": [
{
"MessageId": "48a71eaa-291e-47a3-978b-ce61f3155706",
"Decision": "Maybe",
"BrandName": "CashPower",
"DecisionReasons": [
"LES: Consent not given",
"LES: BureauBcc700Data not collected",
"LES: PrismStockData not collected",
"LES: PreQualificationLite Unknown Result"
],
"CustomerType": "New"
}
],
"MessageId": "dd826184-37e5-4084-935a-ede1c8261745"
}
Then tryajax3.html loads the JSON and tries to display some values – answer 1, 2, 3, and 4 dont display “Maybe” which is what i hoped for
<html>
<body>
<p id="thejson">placeholder json</p>
<p id="answer1">placeholder answer1</p>
<p id="answer2">placeholder answer2</p>
<p id="answer3">placeholder answer3</p>
<p id="answer4">placeholder answer4</p>
<p id="answer5">placeholder answer5</p>
<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function () {
const myObj = JSON.parse(this.responseText);
// These work
document.getElementById("thejson").innerHTML = JSON.stringify(myObj);
document.getElementById("answer5").innerHTML = myObj.MessageId;
// These dont work - they display "undefined"
document.getElementById("answer1").innerHTML = myObj.Decision;
document.getElementById("answer2").innerHTML = myObj.LeadResponses.Decision;
document.getElementById("answer3").innerHTML = myObj.LeadResponses["Decision"];
// This displays [object Object]
document.getElementById("answer4").innerHTML = myObj.LeadResponses;
}
xmlhttp.open("GET", "step1.php");
xmlhttp.send();
</script>
</body>
</html>
The code above shows the following output from the HTML code