1

I am trying to get data from a php script to my angular app. I am using this code to get the data. However it fails and then gives me no information why.

var req = {
        method: 'GET',
        url: 'http://www.hott-source.com/hangman/getMemory.php',
        data: { }
    }

    $http(req).then(function(response){
        alert("WINNER");
        $scope.knownWords = response.data;
    }, function(response){
        alert(response.data);
    });

The PHP script returns

[
    ["A","I"],
    ["BE","BY","DO","GO","IN","ME","MY"],
    ["CAT","COW","DOG","GOD","HIT","MAT","PAT","PIG","RUN","YOU"],
    ["BAND","BIRD","CART","CHIP","DOVE","JUMP","LOVE","READ"],
    ["CHIRP","HAPPY","HORSE"],
    ["CHURCH","HANSON","HITTER","PEOPLE","PRIEST","STRIKE","THOMAS"],
    ["BELINDA","BUILDER","SHOOTER"],
    ["CLAPPING","ELEPHANT"],
    ["COLLECTION"]
] 

which I have verified as json. In the php file I set the header Content-Type to json just before I send it

header('Content-Type: application/json');
echo json_encode($newArray);

response.data alerts as null

How do I get the data from the php script into my $scope.knownWords

Tom Hanson
  • 873
  • 10
  • 39
  • 1
    Did you make request from `http://www.hott-source.com/` or your js located on another domain? – Bob Sponge Mar 01 '16 at 09:10
  • Try with `console.log` instead of `alert` and check the logs in the developer tools. – cezar Mar 01 '16 at 09:11
  • @BobSponge The app is running on my computer. The server is a server I rent elsewhere. – Tom Hanson Mar 01 '16 at 09:16
  • @cezar what would I put into the console.log? nothing has any data in it. – Tom Hanson Mar 01 '16 at 09:17
  • 1
    So, `getMemory.php` must return `access-control-allow-origin: *` http header. More info here: http://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work – Bob Sponge Mar 01 '16 at 09:18
  • @BobSponge can you write that as an official answer so I can mark it correct. That was my problem. Thank you. – Tom Hanson Mar 01 '16 at 09:32

1 Answers1

1

Script getMemory.php must return access-control-allow-origin http header:

header('access-control-allow-origin: *')

More info about CORS here: How does Access-Control-Allow-Origin header work?

Community
  • 1
  • 1
Bob Sponge
  • 4,708
  • 1
  • 23
  • 25