Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda