Reputation: 189
I have looked at other options for posting data to php using angular but haven't had any success. I have an object called "user" that I have logged in js and can see that it's being populated. I am doing the post like
$http.post("./api/register.php", user, config).then(function(response) {
return response.data;
});
with a config object that looks like
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
I have done an echo of a "hello" string in the php and I am able to see that however when I try to echo one of my variables I am unable to. Right now my php looks like
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->firstName;
echo $email;
?>
I have lots of angular experience however only using java spring.
Upvotes: 0
Views: 467
Reputation: 79
var_dump($postdata); whole data from server end, you can find whether data will reach server side or not. If data will not reach to back end, from front end use console.log(data)->check it have json data. please follow below approch to send a data from front end.
Angular Code
$http({
method : 'POST/GET',
url : '/api/register.php',
parm: user // this hold an data
})
.then(
function(response) {
console.log(response);
},
function(erroMessage) {
console.error(erroMessage);
});
Upvotes: 0
Reputation: 19372
I would recommend to not to change headers, keep it as default (application/json):
$http({
method : 'POST',
url : '/api/register.php',
data: user
})
.then(
function(res) {
console.log('SUCCESS', res);
},
function(err) {
console.error('ERROR', err);
});
this php code have to work if You send json object in input:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->firstName;
echo $email;
or how about write normal minimal Slim Framework app:
$app = new \Slim\Slim();
$app->post('/api/register', function () use ($app) {
$body = $app->request->getBody();
var_dump($body);
});
$app->run();
most of modern frameworks have great features to unify request handling.
when I've to do simple api on php I use Slim. here You can see quick start, and make Your own PHP API
Upvotes: 0
Reputation: 171679
You are mixing approaches for application/json
and application/x-www-form-urlencoded
.
Since default for $http
is to send as json and the php is using file_get_contents("php://input")
I suggest you simply remove the config
from the request
$http.post("./api/register.php", user).then(fun....
Upvotes: 2