Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS HTTP Post to PHP

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.

like image 951
Adersh Avatar asked Feb 08 '23 15:02

Adersh


2 Answers

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

like image 168
vp_arth Avatar answered Feb 11 '23 15:02

vp_arth


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);
    });

};
like image 22
Adersh Avatar answered Feb 11 '23 17:02

Adersh