Reputation: 386
I'm getting issue in angular 4 .... I am building hybrid app using ionic 3.
I have to use php as server side language for APIs, I am having issue in posting variables to http.post() request ...
variables are not passed to php file.
Method I'm using to call API from home.ts is:
var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
console.log(re)
})
I'm able to get response from API just fine but the problem is I can't pass the value of variable 'var1' to my API on infoarray.php I'm encoding the request to json ... but didn't get variables
Upvotes: 0
Views: 957
Reputation: 571
Check your PHP code, may be you are missing to get JSON content from Post.
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["param"];
Otherwise try to add params in form data
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers }); // Create a request option
let url = "SERVER_URL";
let body = 'param1='+value1+'¶m2=' +value2;
this.http.post(url, body, options)
Upvotes: 1
Reputation:
You have to stringify the object. Otherwise you will end in getting "[object][object]"
rather than "{var1: 'test'}"
.
JSON.stringify(json);
Upvotes: 0
Reputation: 2678
Use JSON.stringify() and put your headers in RequestOptions class
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let requestOpt = new RequestOptions({ headers: headers });
const bodyStr = JSON.stringify({var: value});
this.http
.post(this.vocabularyPostUrl, bodyStr, requestOpt)
Upvotes: 0
Reputation: 3780
Your params = 'json='+json
will actually result to this: "json=[object Object]". That's because you didn't stringify the object first, which is done as so:
var params = 'json=' + JSON.stringify(json); // "json={"var1":"test"}"
Upvotes: 0
Reputation: 1898
Use JSON.stringify()
method while processing the params:
var json = {var1: 'test'};
var params = 'json='+JSON.stringify(json);
Upvotes: 0