Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting undefined in innerHTML when fetching and displaying data from database using AJAX and JSON
    primarykey
    data
    text
    <p>This is the script I have written for fetching data from the database using AJAX.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function loadJSON() { var data_file = "http://www.idesigns.com.pk/comingsoon/test/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 &amp;&amp; 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(); } &lt;/script&gt; &lt;title&gt;JSON&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;User Details&lt;/h1&gt; &lt;p id="firstname"&gt;John&lt;/p&gt; &lt;p id="lastname"&gt;Doe&lt;/p&gt; &lt;div id='ajaxDiv'&gt;Your result will display here&lt;/div&gt; &lt;button type="button" onclick="loadJSON()"&gt;Update Details &lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>No error in database connection.<br /> no error in fetching and/or in echo of JSON object.<br /> But when I try to display the data using innerHTML, I am getting the following output with undefined instead of getting firstname and lastname from the object.</p> <p><strong>OUTPUT:</strong></p> <pre><code>undefined undefined {"id":"1","firstname":"Bruce","lastname":"Lee"} </code></pre> <p>I can't figure out what's happening. So if anyone can help? Please</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload