Ron Ron - 2 months ago 56x
JSON Question

angular 2 service not calling a php file

i'm learning angular 2 and i make a test to connect to a database, but i get an error that: SyntaxError: unexpected token < in JSON at position 0.

so i have my xampp working on port 80 or 443.
the url of my test ( i'm using angular cli ) is: localhost:4200

this is my attempt. i have a service with this method:

return this._http.get('getusers.php')
.map(res => res.json());

the getusers.php file is located at the public folder.
this is it's content. very basic just to get some results and send them back as json:

// set up the connection variables
$db_name = 'mydb';
$hostname = 'localhost';
$username = 'myusername';
$password = 'mypass';

// connect to the database
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);

$sql = 'SELECT * FROM users';

$stmt = $dbh->prepare( $sql );


$result = $stmt->fetchAll( PDO::FETCH_ASSOC );

$json = json_encode( $result );

echo $json;

so i add that in the component i import the service, initialize it in the constructor and subscribe:

constructor(private _usersService: UsersService) {}

ngOnInit() {
data => this.getUsers = JSON.stringify(data),
error => alert(error),
() => console.log("Finihed")

what am i missing here. i do tons of ajax call but first time with angular. maybe it's the ports? or something else i am missing?

best regards

Ron Ron

so since the situation is a cross domain with the two ports. in your call use the full url with the port: http://localhost:80/yourproject/public/getContacts.php

and in your server side add CORS headers BEFORE outputting:

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');

echo json_encode($result);

since i'm just testing i use the *, but this is not recommended. usuall allow a specific url.