Jump to content
Sign in to follow this  

JSON data from web server running PHP and MySQL Example

Recommended Posts



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:




<!DOCTYPE html>
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;
<div id="id01"></div>
var xmlhttp = new XMLHttpRequest();
var url = 'jsonTestPHP.php';
xmlhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
xmlhttp.open("GET", url, true);
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 +
out += "</table>";
document.getElementById("id01").innerHTML = out;
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 .="]";


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?



Share this post

Link to post
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.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Create New...