angular 2 service not getting a php file json back

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:
import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

export class UsersService {

  constructor(private _http:Http) {}

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


Open in new window

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';

        $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 );

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

Open in new window

and in the component i want to use it i have:
import { Component, OnInit } from '@angular/core';
import {UsersService} from '../users.service';

  selector: 'app-httptest',
  templateUrl: 'httptest.component.html',
  styleUrls: ['httptest.component.css'],
  providers: [UsersService]
export class HttptestComponent implements OnInit {

  getUsers: string;

  constructor(private _usersService:UsersService) {

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

  ngOnInit() {



Open in new window

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
Who is Participating?
Julian HansenConnect With a Mentor Commented:
You are accessing two different servers

The first link on 4200 is probably your node server you are using to test - this does not have a PHP processor so it just returning the file

The second link is to your XAMP server on port 80 - which has a PHP processor.

Try putting the full path to your PHP script in the _http.get( ... ) call.

The app is interpreting the getusers.php relative to its home url which is off the Node server - which is not going to work.
Julian HansenCommented:
Can you post the returned JSON string

F12 - Console - look for the GET output and copy the contents from the Response tab
derridaAuthor Commented:
in chrome i get in the console:
Error: Uncaught (in promise): Error: Cannot match any routes: 'public/getusers.php'

in firefox in the console-> response i actually get the php code. so i guess the < is the opening of the php?

what should i do? do i need to create a route? it is behind the scene.
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

derridaAuthor Commented:
actually, i have refreshed the page and :
Error: Uncaught (in promise): Error: Cannot match any routes: 'public/getusers.php'

doesn't appear anymore
derridaAuthor Commented:
by the way, i notice the difference in the console between chrome and firefox. why is that?
i attach the pictures.
fifrefox consolechrome console
derridaAuthor Commented:
and when i test the php code on its own, not inside the angular project and this is the results:
[{"id":"1","username":"adriel123","email":"","password":"fd9b281c4642ca93ffa6c5da83e142bb6c9c91c7","salt":"caa5423d6b9df8f70789794015c18eaa1f5dc202","first_name":"adriel","last_name":"diaz","company_name":"Yozma","company_logo":"yozma.png","company_url":"http:\/\/\/","role":"1","registration_date":"0000-00-00 00:00:00","phone":"03-5084846","country":"?????","city":"??-????","lang":"he_IL","rate":"1","head":"0"},{"id":"1","username":"adriel123","email":"","password":"fd9b281c4642ca93ffa6c5da83e142bb6c9c91c7","salt":"caa5423d6b9df8f70789794015c18eaa1f5dc202","first_name":"adriel","last_name":"diaz","company_name":"Yozma","company_logo":"yozma.png","company_url":"http:\/\/\/","role":"1","registration_date":"0000-00-00 00:00:00","phone":"03-5084846","country":"?????","city":"??-????","lang":"he_IL","rate":"1","head":"0"}]
Julian HansenCommented:
Ok back up.

Seems one problem just multiplied - lets take them one at a time.

First, your PHP script when called directly seems to return the JSON but when called from Angular it returns the source?
Does not seem possible for it to do that - if PHP is configured on your server than for many reasons - one of them being security - getting the PHP source should not be possible.

Can you check that the URL you are using is the same as the one used in your Angular script. Again you can copy the URL directly from the GET in the console.
derridaAuthor Commented:
i don't understand.
when i try to go to the getusers.php within the angular project i am redirected to the home component. and when i change this redirection and go to: http://localhost:4200/public/getusers.php

i get this in the chrome console:
Error: Uncaught (in promise): Error: Cannot match any routes: 'public/getusers.php'

in order to check my php code independently from the angular project. i have xammp on my local machine, using port 80.
so when i go to: http://localhost/testphp/index.php
i get the results echoed on the page.

when within the angular project i check the firefox console the request i see the actual php code.
the request on firefox console
derridaAuthor Commented:
i suspected that might be connected to the port issue.
now when i put path to that other server i get this:
XMLHttpRequest cannot load http://localhost/testphp/index.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

not allowed. obviously.
so how can i fix this?
i have done tons of ajax calls in the same project. i just give the path and get the results.

how can i do this with angular? i just thought, i'll put the php file in the public folder, and point to it.then handle the results.
i'm confused. also the angular project is inside the htdocs folder, doesn't it means the php should be processed?

how would you do call the database inside an angular 2 project?
derridaAuthor Commented:
also add cause it is important : use CORS headers before outputing
Julian HansenCommented:
CORS will be necessary as the URL you are querying from Angular is not the same as the location where the Angular scripts were loaded from.

What you have is correct - with respect to the headers.

Just to re-iterate - if you are using a NodeJS server to serve your Angular files then your PHP script is not going to work in your application folder.

However, when you deploy your application - assuming it is to an Apache / IIS server that has PHP enabled then you shoudl be able to use the script from the app folder without CORS.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.