Click here to Skip to main content
15,894,128 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I try to reads JSON data from a web server running PHP and MySQL.
I learn code from http://www.w3schools.com/json/json_example.asp
And then I I changed their url with my urlm like this http://localhost/demo.php
But it does not work. I am beginner in JSON and I don't know what happened with my code. Please help me, thank.
Here is my PHP code:
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername,$username,$password);
//check connection
if ($conn->connect_error) 
{
    die("Connection failed: " . $conn->connect_error);
}
$db_selected = mysqli_select_db($conn,"test_json");
if(!$db_selected)
{
	die("Không thể sử dụng DATABASE: ".mysql_error());
}
$sql = "SELECT * from data";
$result = $conn -> query($sql);
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "[") {$outp .= ",";}
    $outp.='{"Name":"'.$rs["Name"].'",';
    $outp.='"Age":"'.$rs["Age"].'",';
    $outp.='"Address":"'.$rs["Address"].'",';
	$outp.='"Phone":"'.$rs["Phone"].'"}';
}
$outp.="]";
$conn->close();
echo($outp);
?>

And here is my JSON
JavaScript
<h1>Customers</h1>
<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:80/demo.php";


xmlhttp.onreadystatechange=function() 
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.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[i].Name +
        "</td><td>" +
        arr[i].Age +
        "</td><td>" +
        arr[i].Address +
        "</td><td>"+
		arr[i].Phone +
        "</td></tr>";
    }
    out+="</table>"
    document.getElementById("id01").innerHTML = out;
}
</script>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900