Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Unable to get value from json response this.responseText?

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

image

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!