Tom Wall
Tom Wall

Reputation: 125

Ajax reading PHP script instead of JSON output

I'm currently trying to use Ajax to use my php array in javascript. Even though I have json encoded the array, set the php content-type, and ajax datatype, it looks like javascript is still trying to process my php script instead of the json it outputs. This is because I always get a 'Unexpected Token <' error (the beginning of my php script).

Here is my ajax:

$.ajax({
  type: 'GET',
  cache: false,
  url: 'api.php',
  dataType: "json",
  error: function(jqXHR, textStatus, errorThrown) {alert(errorThrown);},
  success: function(data) {
    alert(data);}
}); 

And here's my php (filename is api.php):

<?php
header('Content-Type: application/json');
$aliases = array('angry','birds');

echo json_encode($aliases);
?>

I know my php outputs the correct json format, because when I run it in my browser, the output is ["angry","birds"]

Can't seem to figure out what's going on.

Upvotes: 0

Views: 266

Answers (1)

dan-lee
dan-lee

Reputation: 14502

It seems like you're trying to send a request via file system. You're getting the original source code back, because the server/PHP doesn't parse your file.

If you're opening your page via file system (e.g file://some/path/test.html) then the request gets send via file system too. Either you open your page from the server or you need to specify the full qualified location then. I.e. in your case something like http://localhost/api.php.

Upvotes: 1

Related Questions