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;
Related
Iam using the Axio Reactjs code below to post form data to php backend.
when I check record.php files from the chrome browser console and
network. it shows that connection is okay but posted data is empty. it seems like the axios is not sending the data to php backend.
I have tried some solutions here on SO but cannot get it to work. Any work around will be appreciated.
axios({
method:'POST',
url:'http://localhost/mydata/record.php',
rec:{
myParameter1: 'test',
myParameter2: 'test2',
}
}).then(res => {
const data = res.data;
this.setState({ data });
console.log(data);
})
.catch(err => { // log request error
//this.setState({ error: false });
console.error(err);
})
php code
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
//header("Content-Type: application/json");
//check if file_get_contents is enabled
if( ini_get('allow_url_fopen') ) {
echo "enabled";
} else{
echo "not enabled";
}
$data = file_get_contents("php://input");
$request = json_decode($data);
print_r($request);
print_r($data);
?>
In axios docs you can find data tag:
https://github.com/axios/axios#request-config
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
this is what you need, there is no rec property in axios config
Try removing the key rec in your data segment in axios or better still do something along the lines of
{
rec: {
myParameter1: 'test',
myParameter2: 'test2',
}
}
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'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!)
I'm new to angular 2.I'm using http.get() for fetching a data from php file.this is my php file
<?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers: X-Requested-With');
include('connection.php');
$fd=new Connect();
$fd->__construct();
$data=array();
$select=mysql_query("SELECT * FROM userData'")or mysql_error();
$sql=mysql_num_rows($select);
if($sql>0)
{
while($row=mysql_fetch_array($select))
{
}
}
header('Content-Type: application/json');
echo json_encode($data);
?>
Here I used
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');
to get this php file in json file still it's not working.I got whole php file in response instead of json file.
this is my angular 2 component part
export class LoginComponent {
private data;
getData:string;
constructor (private http:Http){}
Getlogin(){
//this.httpService.getUserData()
this.http.get('dev/AngularWithPhp/login.php')
.map(res => res.json())
.subscribe(
data=>this.getData = JSON.stringify(data),
error =>alert(error),
()=>console.log("done"));
}
So what's the problem?give me suggestions...
I am new to ionic1 framework and working on sidemenu ionic app. I want to get list of playlist from Mysql Database.
I have tried this in my controller.js :
.controller('PlaylistsCtrl', function($scope,$http) {
$http.get("#/php/list.php")
.success(function (response) {
$scope.playlists = response.records;
});
console.log($scope.playlists);
})
Php file code :
header("Content-Type: application/json; charset=UTF-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$json[] =array('title'=>'Reggae','id'=>1);
$json[] =array('title'=>'test','id'=>2);
echo json_encode($json);
It gives undefined.
Please help me where I am going wrong.
Your code works asynchron. That is why you add an anonymous function to retrieve the data.
The console.log is called right after the request but before the response is there. So $scope.playlists is empty.
You have to put the console.log inside the success callback to see the result.