Encountering issues with innerHTML displaying undefined results while trying to retrieve and showcase data from a database through the use

This is a sample script for fetching data from a database using AJAX.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadJSON()
{
   var data_file = "http://www.example.com/data/connect.php";
   var xmlhttp;
   if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
   }
   else
   {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }

   xmlhttp.onreadystatechange=function()
   {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
             var jsonObj = xmlhttp.responseText;
             document.getElementById("firstname").innerHTML =  jsonObj.firstname;
             document.getElementById("lastname").innerHTML = jsonObj.lastname; 
             document.getElementById("ajaxDiv").innerHTML=jsonObj;

        }
   }

   xmlhttp.open("GET", data_file, true);
   xmlhttp.send();
}
</script>
<title>JSON Data Retrieval</title>
</head>
<body>
<h1>User Details</h1>
<p id="firstname">John</p>
<p id="lastname">Doe</p>
<div id='ajaxDiv'>Your result will display here</div>
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>

No issues with the database connection.
No problems with fetching and echoing the JSON object.
However, when attempting to show the data using innerHTML, it displays 'undefined' instead of the firstname and lastname from the object.

OUTPUT:

undefined

undefined

{"id":"1","firstname":"Bruce","lastname":"Lee"}

I'm stumped on what might be causing this. Any assistance would be appreciated.

Answer №1

The issue lies in attempting to treat the string as a deserialized object, which does not have properties called firstname and lastname.

To resolve this, you must decode the string into an actual object:

let jsonObject = JSON.parse(request.responseText);

After doing this, accessing properties like jsonObj.firstname will function correctly. It's important to note that once parsed, it is no longer considered a "JSON object." Instead, it becomes a plain object since JSON is a textual format.

Answer №2

To extract information from the JSON, you must first parse it. The variable responseText contains a single string with all the data. When you attempt to access a specific property like responseText.firstname, it will return undefined because strings do not have a firstname property. Instead, use the following code:

var jsonObj = JSON.parse( xmlhttp.responseText );

Now, jsonObj should be an object containing the data sent by your server, rather than just a string.

Answer №3

Include

xmlhttp.responseType = "json"

Make sure to update your code to handle JSON objects properly instead of treating them as plain text.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to trigger a JavaScript alert to notify whether a record already exists or not within a PDO MySQL insert query?

I am working with a MySQL database and looking to insert data from a PHP form using PDO connect. Can anyone help me figure out how to display a JavaScript alert popup in the following scenarios: When a record already exists. When a new record has been ad ...

Updating is not happening with ng-repeat trackBy in the case of one-time binding

In an attempt to reduce the number of watchers in my AngularJS application, I am using both "track by" in ngRepeat and one-time bindings. For instance: Here is an example of my view: <div ng-repeat="item in items track by trackingId(item)"> {{ : ...

Loop through a range of numbers within an array and retrieve the corresponding values

I am faced with a situation where I need to complete the missing gaps between different week ranges stored in a JSON file. The JSON data looks like this: { "Name": "CHT2578/QGA/YEAR/Practical/01 <5-10, 12-16, 21-25, 27-32>", "Descri ...

Using bootstrap can alter the positioning of elements that have margins relative to other elements

After exploring suggestions from my previous post on Stack Overflow, I have implemented a modified version to animate drag movements. While the HTML5 draggable attribute can achieve dragging, its limitations and side effects are something I aim to avoid. ...

Ways to display a variable prior to making an axios request

I have a get request that saves the result in a variable named name_student. How can I access this variable in other methods? Or how should I declare it? Here is the code snippet: getStudent(){ axios.get('https://backunizoom.herokuapp.com/student/2 ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

Leveraging AJAX for seamless PHP execution without page refresh

I have this HTML form: <form class="clearfix" method="POST"> <input name="username" type="text" placeholder="Username:"> <input name="password" type="password" placeholder="Password:"> <textarea name="comment" placeholder="Comment: ...

Angular Navigation alters the view

I want to navigate to a different page using Angular routing, but for some reason it's not working. Instead of moving to the designated Payment Component page, the content is staying on my Main Component. Why is this happening? app.routing.module.ts ...

Is there a way to import a JSON object into Google Sheets?

I need help extracting a specific object result from a JSON URL and importing it into Google Sheets. I am currently using a code found here: https://github.com/bradjasper/ImportJSON However, this code imports the data as an entire table. Is there a way to ...

Having trouble retrieving a customized header from the HTTP response

I've encountered an issue with my Node.js server where I set a custom header. I added the Access-Control-Expose-Headers to allow access from browsers, and it works fine in Chrome and Firefox. However, I'm getting an error in PhantomJS saying "Ref ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...

Momentjs initially indicates that the date is valid, logs the correct date, and displays the accurate duration using .fromNow(). However, this suddenly switches

I am currently working on converting the createdAt date in my Nuxtjs application that is fetched from MongoDB using an express app, with the help of moment.js. Initially, when I check if the date is valid, it shows as valid but then it switches to an incor ...

What is the best way to send a lengthy JSON string using a GET/POST request on Internet Explorer 8?

Having an issue sending a lengthy JSON string from the front-end to PHP on the back-end. Unfortunately, IE8's 2,048 character limit is causing the request to get cut off, regardless of whether it's a GET or POST request. Any suggestions on how t ...

What is the function of the "@" symbol in the ansible code provided within these brackets?

I'm curious about the significance of the @ symbol in this particular line of code and what [@][] represents. This piece of code is utilized in Ansible. Appreciate any insights. json_query("response.result.job | [@][]") The complete code ...

Adding an array to Vue-Kanban blocks can be accomplished by following these steps

I have a web application where I am integrating the vue-kanban component. My goal is to showcase certain objects from my database on the kanban board, but I could use some guidance on how to incorporate them into the display. Below is the array containing ...

Implementing the Jquery click function specifically on a div and not on a class or specific element

I've been trying to keep things simple but haven't found the solution yet (probably because I'm using the wrong terms, unfortunately). Basically, I want my page layout to look like this: Button 1 - Button 2 - text - text - text - text Butt ...

"Utilizing Vue.js to determine whether a checkbox is filled with data or left

My goal is to create a checkbox using vue js without writing a method. I want the checkbox to default to false, and when checked, I want the data "opening_balance" to be an empty array. Conversely, if the checkbox is unchecked, I want it to be omitted when ...

PHP File Upload with AJAX and JSON Integration for Form Submission

Here is a code snippet that demonstrates how to read data from a form, save files in a folder, and write the information to a JSON file: Javascript: var name = $("#name").val(); var image = $("#image")[0].files[0]; var model = $("#model")[0].files[0]; v ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...