I am posting some data to a php
page from angularjs
controller using the $http
method as shown below.
$scope.login = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password
};
$http.post('login.php', data).success(function(response){
console.log(response);
});
};
I know I can retrieve this data in php
using :
$postdata = json_decode(file_get_contents('php://input'), true);
But I was wondering if there is better way in angularjs
so I could use the simple $_POST
in php
to retrieve the data.
In jQuery
we could just simply use $.post
and those are available for php
in $_POST
. Why for angularjs
that is not that simple.
Is there any way to populate $_POST
of php
when we do a $http
post
request in angularjs
. Please help.
You need to convert your request to php known
format.
I use jQuery
$.param
method to build it. You can write your own.
app.config(['$httpProvider', function($http) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http.defaults.transformRequest = function(data) {
return $.param(data);
};
}]);
urlencoded
is followed simple format:
username=Name&password=My%20Password
JSFiddle
Got it working using jQuery
$.param
method. Thanks to vp_arth's answer. I just added this answer as it might help someone. This can be used if it is needed for only one request.
$scope.login = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password
};
$http({
url: "login.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param(data)
}).success(function(response){
console.log(response);
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With