I am trying to send and then get data from PHP on my server, but I don't think it sends the data.
My js code:
angular
.module('h2hApp', [])
.controller('mainCtrl', ['$scope', '$http', function(scope, http) {
scope.initGames = function() {
http({
method: 'POST',
url: 'apis.php',
data: {
url: someUrl
}
})
.success(function(data) {
console.log(data);
});
};
scope.initGames();
}]);
and my PHP file:
<?php
$url = $_POST['url'];
echo file_get_contents($url);
?>
The only thing I get in response is that error:
Notice: Undefined index: url in /my/path/apis.php on line 2
I made this working using jQuery but with AngularJS it doesn't seem to work. I'm new to Angular and I read some other problems like this. I tried things like adding headers and other things but nothing worked.
I am trying to send and then get data from PHP on my server, but I don't think it sends the data.
My js code:
angular
.module('h2hApp', [])
.controller('mainCtrl', ['$scope', '$http', function(scope, http) {
scope.initGames = function() {
http({
method: 'POST',
url: 'apis.php',
data: {
url: someUrl
}
})
.success(function(data) {
console.log(data);
});
};
scope.initGames();
}]);
and my PHP file:
<?php
$url = $_POST['url'];
echo file_get_contents($url);
?>
The only thing I get in response is that error:
Notice: Undefined index: url in /my/path/apis.php on line 2
I made this working using jQuery but with AngularJS it doesn't seem to work. I'm new to Angular and I read some other problems like this. I tried things like adding headers and other things but nothing worked.
Share Improve this question asked Apr 6, 2014 at 10:48 Hristo EnevHristo Enev 2,5411 gold badge23 silver badges32 bronze badges4 Answers
Reset to default 5You can be forgiven for thinking that your PHP script should be expecting data in the $_POST
variable as encoding your data as a query string has traditionally always been the default mechanism.
Angular however encodes the message body as a JSON object by default. As mentioned you could use the params
instead however in the long run I'd argue that it's more flexible to conform on the server-side. For example you can read and decode the message body as follows:
<?php
$data = json_decode( file_get_contents('php://input') );
echo $data->url;
It should be 'params', not 'data'. See http://docs.angularjs/api/ng/service/$http#usage
Be sure to set the HTTP header, sort of like this:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
More info on using Post from AngularJS to PHP
You can use http.post()
method -
Try this the code -
http.post('apis.php', {
url: someUrl
})
.success(function(data) {
console.log(data);
});