Hi I'm trying to get data from a MySQL Database on my Server with a Phonegap App. I'm calling a php file on the server wich is giving me back JSON. I'm trying to do a ajax call on that php file on the server and I want to save the json data in the $scope of angular so I can use it in my HTML. My script looks like this:
function PostsCtrlAjax($scope, $http)
{
var output2 = $('#output2');
$.ajax({
url: 'http://myWebsiteMySQL.ch/landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$scope.posts = data;
},
error: function(){
output2.text('There was an error loading the data.');
}
});
}
</script>
then I want to access the $scope data in the html file like so:
<div id="ng-app" ng-app ng-controller="PostsCtrlAjax">
<div ng-repeat="post in posts" class='postBody'>
<div>{{post.id}}</div>
<div>{{post.name}}</div>
</div>
</div>
but I can't see any data. What am I doing wrong? I'm thankful for any help. I'm trying to solve this problem since 2 days.
my php file on the server looks like this:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xx";
$password = "xx";
$database = "xx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude, l_image AS bild FROM landmarks ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
the Data which is send back is this:
([{"id":"14","name":"Fashion_Coupons","latitude":"9.000000000000","longitude":"9.000000000000","bild":null},{"id":"13","name":"Travel_Coupons","latitude":"3.000000000000","longitude":"4.000000000000","bild":"TopTrendsProgressbar.png"},{"id":"31","name":"Travel_Coupons","latitude":"222.000000000000","longitude":"23212.000000000000","bild":null}]);
See this answer for how to do a JSONP request in angular. AngularJS 1.2 cross origin requests are only supported for HTTP
Note that the documentation says JSONP URLs must contain the string JSON_CALLBACK. http://code.angularjs.org/1.1.5/docs/api/ng.$http#jsonp
$http.jsonp('http://myWebsiteMySQL.ch/landmarks.php?callback=JSON_CALLBACK')
.success(function (data)
{
$scope.posts = data;
});
You can add an error callback to see if that contains any useful info. Chain a .error after the .success callback.
$http.jsonp('http://myWebsiteMySQL.ch/landmarks.php')
.success(function (data) { ... })
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Add watch method for detecting change 'posts' in Your model, something like this:
$scope.$watch('_rows', function() {
$scope.items = $scope.posts;
});