Solved

angular 2 service not getting a php file json back

Posted on 2016-07-24
11
241 Views
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';

@Injectable()
export class UsersService {

  constructor(private _http:Http) {}

  getUsers(){
    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 );

        $stmt->execute();

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

@Component({
  moduleId: module.id,
  selector: 'app-httptest',
  templateUrl: 'httptest.component.html',
  styleUrls: ['httptest.component.css'],
  providers: [UsersService]
})
export class HttptestComponent implements OnInit {

  getUsers: string;

  constructor(private _usersService:UsersService) {
    this.doGetTheUsers();
  }

  doGetTheUsers(){
    this._usersService.getUsers()
      .subscribe(
        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
0
Comment
Question by:derrida
  • 7
  • 4
11 Comments
 
LVL 51

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
0
 
LVL 1

Author Comment

by:derrida
ID: 41727162
hey
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.
0
 
LVL 1

Author Comment

by:derrida
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
0
 
LVL 1

Author Comment

by:derrida
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
0
 
LVL 1

Author Comment

by:derrida
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":"rshtig@gmail.com","password":"fd9b281c4642ca93ffa6c5da83e142bb6c9c91c7","salt":"caa5423d6b9df8f70789794015c18eaa1f5dc202","first_name":"adriel","last_name":"diaz","company_name":"Yozma","company_logo":"yozma.png","company_url":"http:\/\/www.yohgfhgfzma.net\/","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":"rshtig@gmail.com","password":"fd9b281c4642ca93ffa6c5da83e142bb6c9c91c7","salt":"caa5423d6b9df8f70789794015c18eaa1f5dc202","first_name":"adriel","last_name":"diaz","company_name":"Yozma","company_logo":"yozma.png","company_url":"http:\/\/www.ygfdghdgozma.net\/","role":"1","registration_date":"0000-00-00 00:00:00","phone":"03-5084846","country":"?????","city":"??-????","lang":"he_IL","rate":"1","head":"0"}]
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 51

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.
0
 
LVL 1

Author Comment

by:derrida
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
0
 
LVL 51

Accepted Solution

by:
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.
0
 
LVL 1

Author Comment

by:derrida
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?
0
 
LVL 1

Author Closing Comment

by:derrida
ID: 41730775
also add cause it is important : use CORS headers before outputing
0
 
LVL 51

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.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
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…

708 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now