I am trying to make a post request from my angular js, as below
var postData={
firstName:'VenuGopal',
lastName:'Kakkula'
};
postData=JSON.stringify(postData);
$http({method:'POST',url:'http://localhost/blog/posttest.php?insert=true',data:postData,headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function (data,status,headers,config) {
alert('Success' + data);
})
.error(function (data, status,headers,config) {
// uh oh
alert('error' + status + data);
});
I am not sure how to read this POST DATA in my PHP REST webservice.
<?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:Content-Type');
header("Content-Type:application/json");
if(!empty($_GET['insert']))
{
$result=json_decode($_POST['firstName']);
deliver_response(200,"Got the Post data","GotData $result");
}
function deliver_response($status,$statusmsg,$data)
{
header("HTTP/1.1 $status $statusmsg");
$response['status']=$status;
$response['status_message']=$statusmsg;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
I tried the below options
json_decode($_POST['firstName'])
json_decode($_POST['data'])
json_decode($_POST['[postData'])
None of them returned the data, Its always returning the error Undefined index: firstName in F:\xampp\htdocs\Blog\posttest.php on line 10
Can anybody help me how I can read the POST request data sent in php file.
You can also solve this problem without changing code in server and use
$_POST
the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/Most likely it is because you are submitting JSON data which is not automagically populated into the $_POST variable per standard form data.
The work around is to manually parse the input into a variable for use.
Example: