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.