Angular 2 - Unable to do HTTP POST request

Hello everybody,

For the past two weeks I been trying to get this simple script to work without any success and exhausted trying to figure this out. The script isn’t displaying any error messages which makes it that much harder to figure out what it is that I’m doing wrong. When I run the script All i get is the square brackets result of this line (<pre>{{ this.userListReceived | json }}</pre>).

I commented the problem areas as well as a screenshot of the chrome console/network

the script itself isn’t doing a lot other then retrieve a record based on the search value userName: ‘anna’

Side note:
if i change the search value in the PHP file to: $findUser = $_POST['userName'] = 'anna';
I get the following results and which is the correct output.
[{"userID": "3","userName": "anna", "password": "pass3" }]

any help you can provide would be greatly appreciated.

Component

@Component({
    selector: 'get-userlist',
    template: `<h2>Testing</h2>              
               <pre>{{ this.userListReceived | json }} </pre>`,
    providers: [ GetUserListService ]
})

export class GetUserListComponent implements OnInit {   
    private userListReceived: UserType[];
    private errMsg1: string;
    
    constructor(private getUserList: GetUserListService) {}

    getUserListButtonMethod(){      
        this.getUserList.getUserListMethod()
            .subscribe( 
                userData => this.userListReceived = userData,
                error => this.errMsg1 = <any>error,
                ()=>console.log('finished')
            );
    }

    ngOnInit(){
        this.getUserListButtonMethod();
    }
}

service

@Injectable()

export class GetUserListService{
    private userUrl = 'http://testing.dev/angular/app/services/getUserList.php'; 
    private getList: UserType[];   

    constructor( private _http: Http){}

    getUserListMethod(): Observable<UserType[]>{       
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        var findU = JSON.stringify({userName: 'anna'}); // problem area. assuming findU isn't passed through

        return this._http
                .post(this.userUrl, findU , options) //problem area
                .map((res: Response) => res.json()) 
                .catch (error => <any>error);                
    } //END - getUserListMethod
} //END of class

PHP file

<?php 
	require_once('dbtesting.php'); 
	$dbcon = Connection::getConnection(); 
	$findUser = $_POST['userName'] ; //problem area, assuming $findUser isn't receiving the value in this case userName for search	
	Try{
		$STMT = $dbcon ->prepare("SELECT * FROM tbl_angular
		                                   WHERE userName = '$findUser' ");	
		$STMT->execute();
		$getUserlist = $STMT->fetchAll(PDO::FETCH_ASSOC);	
	}
	catch(PDOException $e){ echo 'Unable to find user: ' . $e->getMessage(); }	
	echo json_encode($getUserlist);	
?>

Chrome console & network output

Hi @robin01,

The problem is that when you post JSON data to PHP, you can’t access it via the $_POST superglobal like you normally would for form data. Instead, you have to retrieve it from the request body manually:

$data = json_decode(file_get_contents("php://input"));

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.