1

I have a php script to return json through GET, the code is as below

<?php
$output = //generate json data;
header('Content-type: application/json');
echo json_encode($output); ?>

I host this php in local host, so when i access http://localhost/test.php , i am able to see json data correctly.

Then I have a page using AngularJS, like below

<h1>{{myWelcome}}</h1>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http({
    method : "GET",
    url : "http://localhost/test.php"
  }).then(function mySucces(response) {
      $scope.myWelcome = response.data;
      alert("success");
    }, function myError(response) {
      $scope.myWelcome = response.statusText;
      alert("fail");
  });
});

I run the page, nothing displayed in the UI. I didn't get any alert. Which means it's neither success nor fail. If I switch the URL to be other api. for example

url : "http://congress.api.sunlightfoundation.com/legislators?apikey=xxx"

I can get response correctly. It means my js code is good. So my question is, why i can't get json response from my localhost php. Is there anything wrong on my php, or it's my js's problem?

I tried to search in stackoverflow, some people suggest this but it didn't help.

$http.get('http://localhost/angmysql/api.php').success(function(response) {
    $scope.users = response.data;
}); 

Thanks for the comments from @jay. Look at console, Here is the thing.

XMLHttpRequest cannot load http://127.0.0.1/test.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access.

user2105500
  • 197
  • 1
  • 2
  • 8
  • can you move the alert as the first line in the function..rather than it being the last line...the call should either fail or work... – Jay Rajput Oct 31 '16 at 02:30
  • yes. it dosen't change anything. If i switch to the working URL. i am able to see alert(). However, using localhost, i can't see any alert. – user2105500 Oct 31 '16 at 02:33
  • does firebug console shows anything? – Jay Rajput Oct 31 '16 at 02:34
  • since the code works with one URI and not with another, I would think it to be some kind of security issue..Generally browser will not allow loading data from a different domain to restrict CSRF attack...which domain is your page loaded from? discussion on single origin policy to avoid CSRF attack: http://security.stackexchange.com/questions/58755/how-are-ajax-requests-vulnerable-to-csrf-attacks-if-the-same-origin-policy-is-ap – Jay Rajput Oct 31 '16 at 02:38

0 Answers0