I'm working on a project in which I want to read PHP data in HTML using JSON
Here is my JavaScript code:
var xmlhttp;
var jsonResponse = "";
window.onload = function() {
alert('window.onload fired!');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "../getproduct.php",true);
alert('Constructed XMLHTTP request!');
xmlhttp.send();
xmlhttp.onreadystatechange = dataReturn;
document.getElementById('getBtn').addEventListener('click', getData, true);
}
function dataReturn() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
jsonResponse = xmlhttp.responseText;
//jsonResponse = eval('(' + jsonResponse + ')');
alert(jsonResponse);
}
}
var div = document.getElementById('result');
function getData() {
alert('getData()');
// Parsing the txt JSON string
obj = jsonResponse;
document.getElementById('result').innerHTML = obj;
txt1 = JSON.parse(obj);
alert(txt1);
employees = txt.products;
// Looping through object employees
for (i = 0; i < employees.length; i++) {
var p = document.createElement('p');
p.innerHTML = '<b>First name:</b>' + employees[i].menuid + ', <b>Last name: </b>' + employees[i].name;
div.appendChild(p);
}
// Generate a new JSON string based on current JS object.
jsonString = JSON.stringify(obj);
alert(jsonString);
}
Using this code I am able to read PHP file as a json
Here is the output of PHP file:
{
"products": [
{
"menuid": "9",
"name": "Cable Managementdsdsd",
"description": "fgfgfg",
"location":"CableTray.jpg"
}
]
}
I am unable to read this JSON data in JavaScript.
{"products":[{"menuid":"9","name":"Cable Managementdsdsd","description":"fgfgfg","location":"CableTray.jpg"}]}now i want this to be shown in DIV ..