2

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:

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


    $stmt->execute();


    $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() {
     this._usersService.getUsers()
       .subscribe(
         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

3
  • That "SyntaxError: unexpected token < in JSON" could mean that your php is with error. Make sure you have a completely working php code before anything. (you can use chrome's POSTMAN extension for some fancy requests) Commented Jul 23, 2016 at 15:58
  • Since you aren't sending anything, access getusers.php from the browser. What do you see? Commented Jul 23, 2016 at 16:00
  • i know. the first thing i did was to check the file initself, i do a var_dump and do get the data Commented Jul 24, 2016 at 5:26

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to subscribe to the the ajax call to work ; Who ever is calling the getUsers method should subscribe to it :

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

Let's say you're calling get method here :

 myOtherFunction(){
     this.getUsers.subscribe((response)=>{
           console.log('response',response);

     })

}

1 Comment

hey, sorry i forgot to add this. in my component i import the service and then this: ` ngOnInit() { this._usersService.getUsers() .subscribe( data => this.getUsers = JSON.stringify(data), error => alert(error), () => console.log("Finihed") ); }`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.