Angular 6 :
import {Injectable} from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class GetData {
constructor( private http: HttpClient ) { }
post( ) {
data = [ {username : 'test',password : '1234' }];
return this.http.post('login.php' , data );
}
}
PHP : login.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
?>
How can i get data from Angular 6 that is [Object] into $username , $password
**
"$_POST" and "$_REQUEST" is not available for me.
**
Try this:
import {Injectable} from '@angular/core';
import { HttpClient,HttpParams } from '@angular/common/http';
@Injectable()
export class GetData {
constructor( private http: HttpClient ) { }
post( ) {
let data= new HttpParams()
.append("username", "test")
.append("password", "1234")
return this.http.post('login.php' , data );
}
}
For some reason Angular seems to send POSTs that end up in php://input
instead of $_POST
, and then you can json_decode
them into an object and use them.
On the Angular side - I'm just tossing data at the server, I care not about the response... tried getting it going without the whole subscribe()
thing but it wouldn't POST at all for me at that point... Note taht there is a private http: Http
in the constructor for the TS file/component/class this is in...
postChatMessage(room: string, user: string, msg: string, timestamp: number) {
var cmsg = new ChatMessage(room, msg, user, timestamp);
return this.http.post(BASEURL + "/chat", cmsg)
.subscribe(
(v) => {},
response => {},
() => {}
);
}
The PHP on the back end that handles the POST that sends - yes, I'm being lazy and just storing the whole JSON string sent plus a few other things, but easier for me to deal with for a quick school thing -
if (($_SERVER['REQUEST_METHOD'] == "POST") &&
(strpos($_SERVER['REQUEST_URI'], "/json_service/chat") === 0)) {
$d = file_get_contents("php://input");
$d = json_decode($d);
$d->timestamp = time();
$q = "insert into json_chat values(?,?,?,?)";
$a = array(null, time(), $d->room, json_encode($d));
$res = executeQuery($q, $a);
print(json_encode(array($res[0]))); // boolean fwiw
exit;
}