Reputation: 142
I want the response in JSON but I get the wrong response. I am learning AngularJS. Please help me.
I am using fetch.php
code below:
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "ghanshyam";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname );
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM `table`";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$r[] = $row;
}
} else {
echo "0 results";
}
header('Content-Type: application/json');
echo json_encode(($r));
$conn->close();
?>
and also using HTML code below
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="comen.js"></script>
<body>
<div>
<p>hello</p>
<table ng-app="myApp" ng-controller="myCtrl" >
<tr ng-repeat="x in myWelcome track by $index">
<td> {{ x.one}} </td>
<td> {{ x.two }} </td>
<td> {{ x.three }} </td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("fetch.php")
.success(function(response) {
console.log(response.data);
$scope.myWelcome = response.data;
});
});
</script>
</body>
</html>
I get the response as shown below:
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "ghanshyam";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname );
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM `table`";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$r[] = $row;
}
} else {
echo "0 results";
}
Upvotes: 0
Views: 487
Reputation: 41447
.success
is deprecated since angular version 1.4.Since you are using version 1.6, use then
to catch the response.
$http.get("fetch.php")
.then(function(response) {
console.log(response.data);
$scope.myWelcome = response.data;
});
make sure to define the $r
as an array also.
$r = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$r[] = $row;
}
} else {
echo "0 results";
}
Upvotes: 1