0

I am trying to connect my angular app with PHP. I am getting a error

Unexpected token < in JSON at position 0

This is my code :

PHP :

<?php 
$successreturn[]=array(
        "id"=>"any",
       "firstname"=>"any",
      "lastname"=>"any",
    "dateofbirth"=>"any",
    "city"=>"any",
    "gender"=>"any");
header("Access-Control-Allow-Origin: *");
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
    echo "Connection Problem".mysqli_connect_error($conn);
}

$sql= "SELECT * FROM Employees";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
    $value=0;
if(!$result){
    echo "Connection Failed " .mysqli_connect_error($result);
 }
 while($row = mysqli_fetch_assoc($result)){

    $successreturn[$value]['id']=$row['id'];
         $successreturn[$value]['firstname']=$row['firstname'];
         $successreturn[$value]['lastname']=$row['lastname'];
         $successreturn[$value]['dateofbirth']=$row['dateofbirth'];
         $successreturn[$value]['city']=$row['city'];
         $successreturn[$value]['gender']=$row['gender'];
         $value++;

        };
echo json_encode($successreturn);


?>

Service:

import {Injectable} from '@angular/core';
import {Http,Response,Headers,ResponseOptions} from '@angular/http';
import {Observable} from 'rxjs';
import {Data} from './data';

@Injectable()
export class DataService{
    empurl="http://localhost/php/connect-employee.php";
    constructor(private http:Http){}

    getDetailsFromDataBase():Observable<Data[]>{
        return this.http.get(this.empurl)
        .map(this.extractData)
        .catch(this.HandleError)
    }

    private extractData(res: Response){
            let body= res.json();
            return body.data() || []
    }
    private HandleError(error: Response| any){
        console.log(error.message || error);
                return Observable.throw( error.message || error);
        }
}

Component :

import { Component,OnInit } from '@angular/core';
import {DataService} from './data-service';
import {Data} from './data';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    datas : Data[];
    errorMessage : String;
    firstName : String;
    lastName : String;
    Gender : String;


    constructor( private dataservice: DataService){}
    ngOnInit(){
        this.fetchData();
    }
    fetchData(): void{
        this.dataservice.getDetailsFromDataBase()
            .subscribe(datas=> this.datas = datas, 
                        error => this.errorMessage = <any>error)
            console.log(this.datas);
    }

}

this is my code. I dont know if I am doing wrong in my PHP code or in my Services. I think i am not getting a JSON data from my PHP file. How can i solve this? Any help would be appreciated.

Prakash
  • 71
  • 2
  • 11
  • `Unexpected token <` suggests you're getting HTML/XML, not JSON. – jonrsharpe Jun 24 '17 at 21:09
  • How do i convert it into JSON? Isnt json_encode() meant to Covert into JSON value?? – Prakash Jun 24 '17 at 21:11
  • One likelihood is that you are actually getting a 404 not found error, because some file being loaded doesn't exist. Now for Angular, you probably have 404s redirected to the index.html page, because that is required. Check the network traffic in the browser dev tools to see if the index.html file is unexpectedly being returned for some request. – Rob Zuber Jun 24 '17 at 21:15
  • It's not getting redirected to index.html. Websocket is called but it is pending. There a Caution: request is not finished yet. – Prakash Jun 24 '17 at 21:29
  • Have you checked your network tab and what you are receiving? You have a couple of problems in your Angular code, but they aren't causing this error. Most probably your error is in php file, where as `echo json_encode($row);` isn't returning valid JSON, so you need to check that, OR more likely, your if-statement is truthy and you are actually returning `echo "Connection Failed " .mysqli_connect_error($result);` which you have **NOT** `json_encode`:d. So try and `json_encode` that and see what happens. And maybe add an `else` to returning `echo json_encode($row);` if `if` is truthy. – AT82 Jun 25 '17 at 10:08
  • also is `"SELECT * FROM Employees"` just turning one row or an array? Because now you are just returning one row (object). – AT82 Jun 25 '17 at 10:12
  • I just changed my PHP code now its returning a JSON when i run the PHP file. `[{"id":"1","firstname":"sandeep","lastname":"Chetikam","dateofbirth":"1993-09-02","city":"visakhapatnam","gender":"male"},{"id":"2","firstname":"dhruv raj","lastname":"nadimpally","dateofbirth":"1993-09-09","city":"visakhapatnam","gender":"male"}]` But still i am getting undefined. and the same error. – Prakash Jun 25 '17 at 11:08
  • Undefined error is: That is because you are console logging outside the callback, you need to put it inside `.subscribe` Check this one: https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2 – AT82 Jun 25 '17 at 11:22
  • In services its going for the Handle error. Why is it like that? When i run the PHP file its returning a JSON value i dont think its going to the `echo "Connection Failed " .mysqli_connect_error($result);` Am i calling it wrong in Services. I am updating my **PHP code** Please check it and let me know if i am doing anything wrong. – Prakash Jun 25 '17 at 11:24
  • Please check the network tab in developer tools and see what you are receiving – AT82 Jun 25 '17 at 11:25
  • For the PHP file, i am getting a JSON value as response. But after that, a **Web Socket** is called and it's in **101 status** – Prakash Jun 25 '17 at 12:09
  • I am sry but when i check it now . I am not getting any response. Its Showing response status: 404. Please let me know whats wrong with the code. – Prakash Jun 26 '17 at 06:49
  • I have changed the `.map(res => this.data = res.json())` and its working. Now i have a small doubt what would be the link for the Update and Create Function for the Php to get the Id. – Prakash Jun 27 '17 at 12:41

0 Answers0