Unable to get value from json response Here is my html.
index html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<br>
<br>
<p id="demo"></p>
<p id="demo1"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML ="JSON = " this.responseText;
document.getElementById("demo1").innerHTML = "first name = " this.responseText.fname;
}
};
xhttp.open("POST", "/test.php", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
}
</script>
</body>
</html>
and test.php
<?php
echo '{"fname":"sumith","lname":"emmadi"}'
?>
when I click request data button it will send a POST request to "/test.php" and get response as
{"fname":"sumith","lname":"emmadi"}
I want to get value of fname but it is showing undefined
CodePudding user response:
You will get a response inside xhttp.responseText
or this.responseText
.
And to get fname and lname, first parse result using JSON.parse and get fname
, lname
out of it using Destructuring assignment
const { fname, lname } = JSON.parse(xhttp.responseText);
// To show in DOM
document.getElementById("demo").innerHTML ="JSON : <pre> " xhttp.responseText "</pre>";
document.getElementById("demo1").innerHTML = "first name = " fname;
CodePudding user response:
You need to parse the JSON into an object before you can extract the specific property values. e.g.
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(responseText);
document.getElementById("demo1").innerHTML = "first name = " data.fname;
}