Jump to content

JSON data from web server running PHP and MySQL Example


rich_web_development

Recommended Posts

Hi,

 

I'm trying to follow the JSON example at http://www.w3schools.com/json/json_example.asp

 

I have adjusted the code a little but the code is as follows:

 

jsonTest.html

 

<!DOCTYPE html>
<html>
<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = 'jsonTestPHP.php';
xmlhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr.Name +
"</td><td>" +
arr.Bedrooms +
"</td><td>" +
arr.Length +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
jsonTest.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$result = $conn->query("SELECT name, bedrooms, length FROM holidyhomes");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["name"] . '",';
$outp .= '"Bedrooms":"' . $rs["bedrooms"] . '",';
$outp .= '"Length":"'. $rs["length"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>

 

So I have changed the var url = "http://www.w3schools.com/website/customers_mysql.php"; from the jsonTest.html to var url = 'jsonTestPHP.php';

 

When I run this I get "Invalid character: var arr = JSON.parse(response);"

 

I just want to be able to grab the data from my database and display it on screen using JSON.

Can anyone help me understand why I'm getting this Invalid character error or tell me if I'm going about this the totally wrong way?

Thanks

 

Link to comment
Share on other sites

That error message sounds like the response is not valid JSON. What is the response? You can use your browser's developer tools to look at the request and see what the response is also.

 

Don't try to manually output JSON code. Build an array of your data in PHP and then use json_encode to convert it to JSON.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...