Reputation: 391
Right now I have a basic post request using the $http service in angular. I'm seeing everything find in console.log with a status of 200 (successful), but in PHP no luck. I've tried using JSON_decode, I've tried the $_POST (var_dump) no luck. Please assist if you can think of a solution.
app.js
var postData={
firstName:'something',
lastName:'here'
};
postData=JSON.stringify(postData);
$http({method:'POST',url:'sendmail.php',data:postData,headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function (data,status,headers,config) {
console.log('Success' + data);
})
.error(function (data, status,headers,config) {
// uh oh
console.log('error' + status + data);
});
sendmail.php
$args = json_decode(file_get_contents("php://input"));
echo $args->firstName;
In my php file I am getting the following error.
Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/my-new-project/sendmail.php on line 3
however, in my console.log I am getting:
Successsomething
Also, I have a live site with the same problem.
Just to reiterate no matter what I do, (add headers, JSON decode) PHP array remains empty.
Upvotes: 2
Views: 1017
Reputation: 1688
This actually has to do with how Angular passes the data. By default is serialized to JSON format which creates the issue with PHP.
I'm going to presume that your data is coming from some inputs or something like that. It's better to use ng-model on the form fields
Basically you have to pass a custom header in the request. In this code I'm just using a single input:
$http({
method : 'POST',
url : 'your_url',
data : 'data-name=' + $scope.yourValue,//in PHP then you look for $_POST['data-name']
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
// success callback
function(response){
// success code
},
// error callback
function(response){
// success code
}
);
In order to get a better grasp of how to do this read this article:
Upvotes: 0
Reputation: 1308
When you $http.post() in AngularJS, you can get the parameters in PHP from the $_POST array like:
echo $_POST['firstName'];
If $_POST is empty, then you a problem somewhere else.
Try isolating your problem. You can use Postman, HTTPRequester or any other Firefox/Chrome plugin to simulate a request to your PHP script.
Make your PHP script work first, then make your AngularJS post request work.
Upvotes: 1