I am trying to get data from my server in a HTML file.
I tried w3 schools code but when I try to use my server link it prints nothing.
Here is the angular code:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http
.get("http://rabikhan.net23.net/Bitm_Student_Project/src/test.php")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
and the php code
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("mysql4.000webhost.com", "a1724083_rhk", "r7224191", "a1724083_tour2");
$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 ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
Question
How can I have echo($outp);
print the desired information?
change your php to:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("mysql4.000webhost.com", "a1724083_rhk", "r7224191", "a1724083_tour2");
$result = $conn->query("SELECT CompanyName AS Name, City, Country FROM customers");
// create an empty output array
$output = array();
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
// add record to output array
$output.push($rs);
}
$conn->close();
// return output array as proper json
echo json_encode($output);
?>
I also noticed that you have some analytics code in your php response pointing to http://stats.hosting24.com/count.php, make sure not to append it to your JSON responses
</div>