angular 2 service not getting a php file json back

Posted on 2016-07-24
Last Modified: 2016-07-27
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
Question by:derrida
  • 7
  • 4
LVL 55

Expert Comment

by:Julian Hansen
ID: 41727129
Can you post the returned JSON string

F12 - Console - look for the GET output and copy the contents from the Response tab

Author Comment

ID: 41727162
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.

Author Comment

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

doesn't appear anymore
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.


Author Comment

ID: 41727173
by the way, i notice the difference in the console between chrome and firefox. why is that?
i attach the pictures.
fifrefox consolechrome console

Author Comment

ID: 41727179
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"}]
LVL 55

Expert Comment

by:Julian Hansen
ID: 41727404
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.

Author Comment

ID: 41727419
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
LVL 55

Accepted Solution

Julian Hansen earned 500 total points
ID: 41727440
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.

Author Comment

ID: 41727453
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?

Author Closing Comment

ID: 41730775
also add cause it is important : use CORS headers before outputing
LVL 55

Expert Comment

by:Julian Hansen
ID: 41730994
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.

Featured Post

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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question