Gopal Chandak
Gopal Chandak

Reputation: 385

variable posted from angular to php using $http.post() is not working

I posted a variable from a angularjs controller to a php file in the same folder using $http.post() method. But in the php page I am able to retrieve the variable. The variable is being undefined.

Here is the angular code

$scope.checkout = function(){
         $http({
         url:"checkout.php",
         method : 'POST',
         data :{
            'total':$scope.total
        },

        headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
    }).success(function(data, status, headers, config) {
        window.location.href = 'checkout.php'
    }).error(function(data, status, headers, config) {
       console.log("not done");
});
    }

and here is the php code

<?php
$_SESSION['bill_amount'] = $_POST['total'];
echo $_SESSION['bill_amount'];
?>

But I am getting the error that total is undefined.

Upvotes: 2

Views: 97

Answers (2)

Gopal Chandak
Gopal Chandak

Reputation: 385

I found the answer. I created a middle page called middleware.php where I am storing the post data to session variables and on success I am redirecting to checkout.php and using the post values through session variables.

Upvotes: 1

Iftikhar uddin
Iftikhar uddin

Reputation: 3182

You are sending data but Angular by default send it as in JSON format and you need to decode the JSON so in your php file decode the JSON by using json_decode function.The full code is given below:

<?php
 $data = json_decode(file_get_contents("php://input"));
 $total = $data->total; // $_POST['total'];
 $_SESSION['bill_amount'] = $total;
?>

Upvotes: 1

Related Questions