Sorry but I'm a newbie to web development. I've been playing around with some JSON objects lately and have been using some example from W3school site - 'http://www.w3schools.com/json/json_example.asp.'
The example retrieves data from MYSQLi db and injected it into a JSON object. I've been using this example to create a dynamic site however my problem is I'm not sure if you need a db to store the data in the first place. Can JSON object be directly retrieved from a server?
The response from the server is parsed as a JSON object. i.e. var = JSON.parse(response)
<!DOCTYPE html>
<html>
<head>
<title>XMLHTTPREQUESTEXAMPLE</title>
</head>
<body>
<p id="id01"></p>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "//http:URL";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}else{
document.getElementById("id01").innerHTML = "Server not responding";
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table><tr><th>Name</th><th>Job Title</th><th>Room No</th><th>Tel Ext</th><th>Email</th></tr>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].JobTitle +
"</td><td>" +
arr[i].RoomNo +
"</td></tr>"
arr[i].TelExt +
"</td></tr>"
arr[i].Email +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
The example php script on the server from the W3 school site.
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT CompanyName, City, Country FROM Customers");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Country":"'. $rs["Country"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>