I'm trying to call a web service from angular 5 to PHP.
I'm using POST method but I have trouble retrieving data in PHP side.
Send data is shown in payload but it's not retrieved in php side.
Angular service.ts
this.URL = "http://localhost/angular/WEBSERVICE_PHP/test.php";
const headers = new Headers();
headers.append('Content-Type', 'application/json');
let data = 'visitor_id=55';
return this.http
.post(this.URL,JSON.stringify(data),{
headers: headers
})
.map( Response => console.log(Response) );
PHP PAGE
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET");
header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies
header('content-type: text/plain');
header("content-type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-
Requested-With");
header("Access-Control-Max-Age: 172800");
if(isset($_POST))
{
// $post = 'test data'; // This data get sent
// return $post;
echo $post = $_POST['visitor_id'];
return $post;
}
When "posting" JSON, you won't see $_POST.
Instead do this:
$json = file_get_contents('php://input');
$array = json_decode($json, true);
If it MUST be $_POST, you can assign the $array to $_POST.
The other solution is from the Angular side, instead of sending the JSON string, send a proper post! (I'm not an Angular man, maybe someone can comment and I'll add the code!)
Related
I'm trying to do a basic POST request from my ionic angular app using the HttpClient from Angular. From that POST, I need to pass the payload to PHP file for me to manipulate another function in the PHP.
I can seem to echo the whole data, but trying to get the single value gives an error.
Below is my code under home.ts
test() {
let data = {
firstname: "John",
lastname: "Wick"
}
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json; charset=UTF-8');
headers.set('Access-Control-Allow-Origin', '*');
headers.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
this.http.post(this.php_url, data, {headers: headers}).subscribe((res) => {
console.log("Posted successfully")
console.log(res);
}, (err) => {
console.log(err.error);
});
}
In my index.php file, I have the code below.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Content-Type: application/json');
$json = file_get_contents('php://input');
echo $json->firstname;
?>
I am able to echo $json, but not when trying to get the single value. How do I get the single value from the JSON data?
you have to use
print_r($json['firstname']);
insted of
echo $json->firstname;
I have problem with request POST in fetch function. I make REST API with react and PHP and I get error Access-Control-Allow-Origin is required. I have this header in my web api. This is my code (begin) in PHP:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");
header("Access-Control-Expose-Headers: access-control-allow-origin");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");
and in React:
//method = POST
//body = {"name":"test","body":"test"}
const apiCall = (url, method, body, resolve, reject) => {
fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(body)
}).then(resp => {
if(resp.ok) {
resp.json().then(json => resolve(json));
}
else {
reject(resp);
}
});
}
I try to communicate with other server and api - result was the same.
Screen with error in Google Chrome browser:
screen
Please help.
You have to add the CORS MODULE and Proxy in Server.
This question already has answers here:
PHP Get JSON POST Data
(1 answer)
Reading JSON POST using PHP
(3 answers)
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 4 years ago.
I just created an angular 7 project
I try to send a post with some data, nothing is set in the header part
so on the server side I only get the php script called, nothing in the $_POST array
this code works fine in angular 5, I should see the data in the header log in chrome
createPostOptions() {
let headers = new Headers({
'Content-Type': 'application/json',
});
let options = new RequestOptions({ headers: headers, withCredentials: true });
return options;
}
getParts(): Observable<any>
{
return this.http.post('http://localhost/site/data.php',{command:'getParts'}, this.createPostOptions())
.pipe(map((response: Response) => {
return this.processData(response,this.router);
}));
}
php code:
function cors()
{
header("HTTP/1.1 " . "200" . " " . "OK");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header('Access-Control-Allow-Headers: Accept, Content-Type, Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Methods, X-Requested-With, X-API-KEY, X-Auth-Token, X-Requested-With, Authorization, Content-Range, Content-Disposition, Origin, Access-Control-Request-Method');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Origin: '."http://localhost");
header('Access-Control-Allow-Credentials: true');
}
//-----------------------------------
if($_SERVER['REQUEST_METHOD']=="OPTIONS")
{
cors();
}
else
{
...
}
I should see something like this
Any help apreciated
Since you are sending json in the body, but not as post parameters, you need something like
$jsonInput = file_get_contents('php://input');
$obj = json_decode($jsonInput);
$command = $obj->command;
I'm trying to POST data to a PHP backend and receive back the values and push it into an array. Hence, I created a function to do just that. However, I'm not to change the API on the backend (written in PHP). So I cannot change it to suit my normal methods of using POST.
This is my function
test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).subscribe(data => {
this.result = data; // get data in result variable
this.items = JSON.stringify(this.result); // then convert data to json string
// console.log(this.items);
this.allData = JSON.parse(this.items); // parse json data and pass json string
// console.log(this.allData.length); // got result of particular string
this.array = [];
for (var i = 0; i < this.allData.length; i++) {
this.array.push({
data1: this.allData[i].data1,
data2: this.allData[i].data2,
})
}
console.log(this.array[0])
})
}
And this is an example function on the backend
else if($_POST['method']=="getThis"){
global $conn;
mysqli_select_db($conn, $_POST['db']);
$name="";
$result=array();
$r=mysqli_query($conn,"select data1,data2 from table");
while ($rs = mysqli_fetch_array($r,MYSQLI_ASSOC)){
array_push($result,$rs);
}
echo json_encode(array("result"=>$result));
}
So how do I actually get it to post? I'm stuck here. I usually post with JSON and then decode the JSON on the backend. But this time around I'm not developing the backend and not changing it so gotta use the one provided.
Posting using POSTMAN with this
method=getThis&db=myDatabase
works well. Not sending JSON just a text. So how do I actually achieve this in Ionic.
You could try it that way. It works for me:
First import:
import { map } from "rxjs/operators/map";
Your function:
test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).pipe(
map(res => res.json())
).subscribe(response => {
//Here your code
// 'response' is json
});
}
Since the data you are sending is in plain text, you will need to add a header mentioning the content type.
import { HttpHeaders } from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'text/html'
})
};
this.http.post("API URL", data, httpOptions).subscribe()
PHP side should be return JSON and told browser content type is application/json, please test your code base on one simple page.
//demo.php
<?php
$data = ['message' => 'Hello world.'];
header("Content-Type: application/json; charset=UTF-8");
//If allow cross domain and not configration in Ngix/Apache
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Accept-Encoding, X-Requested-With, Content-Type, Origin, Accept, Authenticationtoken");
echo json_encode($data);
And please try http access demo.php again.
I am new angular developer, test app is working fine in localhost. but in the server http post, put, delete all not working. server return 403 forbidden error and also blocked my ip if hitting the page frequently.
TypeScript:
addHero(hero: Hero): Observable<Hero>{
const url = `${this.apiUrl}post.php`;
return this.http.post<Hero>(url, hero, httpOptions).pipe(
tap((hero: Hero) => this.log(`Added id ${hero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
PHP:
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');
$data = json_decode(file_get_contents('php://input'), true);
Thanks for the help.
Use:
$data = $_POST;
instead.
$_POST is an array with the post data.