0

I am using angular js script to fetch data from external php file encoded in json in html page. I have used $http.get(page2.php) method to fetch json encoded array written in another file. But the problem is its not showing any output just a blank screen I dont know where am I doing wrong.

Here's page1.html

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myapp',[]);
app.controller('myctrl',function($scope,$http){
$http.get('page2.php').success(function(response){
$scope.names = response;
});
});
</script>
</head>
<body>   
<div>
<table ng-app="myapp" ng-controler="myctrl" >
<tr ng-repeat="x in names">
<td>{{ x.id }}</td>
<td>{{ x.name }}</td>
<td>{{ x.age }}</td>
</tr>
</table>
</div>
</body>
</html>

Here's page2.php

<?php

$con = mysqli_connect('localhost','root','','practice');
if(!$con){
die("couldnt connect".mysqli_error);
}
$query = "SELECT * FROM records";
$result = $con->query($query);
$r = array();
if( $result->num_rows>0){
while($row = $result->fetch_assoc()){
$r[] = $row;
}
}
$res = htmlspecialchars(json_encode($r));
echo $res;
?>

I can't figure out where am I doing wrong.

4
  • You're error checking your connection, but not the query. Commented Jul 7, 2015 at 12:44
  • Is there any error on browser console ? Check your connection to database .Check by adding console.log(response); in success callback Commented Jul 7, 2015 at 12:45
  • NO error just a blank screen Commented Jul 8, 2015 at 7:16
  • query is fine working good but it display nothing.. @JayBlanchard Blanchard Commented Jul 9, 2015 at 5:14

1 Answer 1

2

If you're sure you're getting data from your query, you just need to send it as JSON. Add this before the echo $res; line:

header('Content-Type: application/json');

Sign up to request clarification or add additional context in comments.

7 Comments

it is showing the converted data when i run php file alone but as i call from html page it shows nothing. @kiswa
Try using something like Postman and see what that shows when it calls the PHP file.
whats that for ?? @kiswa
It lets you test an API directly.
I am not using the api key...how would that resolve my issue.??
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.