简体   繁体   中英

how to post a json array from angularjs controller to php page

I used the $http.post() method. Here is the code

$scope.checkout = function(){
         $http({
        url:"checkout.php",
        data : $.param($scope.orders),
        method : 'POST',
        headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
    }).success(function(data, status, headers, config) {
        $scope.sdata = data;
    }).error(function(data, status, headers, config) {
        $scope.status = status;
});
    }

My json array is stored in $scope.orders and i want to post to checkout.php which is in the same folder.

And in the php page my code is

<?php
$data = file_get_contents("php://input");
    $postData = json_decode($data);
    foreach ($postData as $post) {
    echo $post->name;
    echo "<br>";
    echo $post->price;
    echo "<br>";
    echo $post->quantity;
    echo "<br>";
    echo "<br>";
}
?>

But its not working.

And please tell me how to redirect to checkout.php. Basically I am posting this data on a button click and i want to redirect to checkout.php after the data is posted.

Your php is expecting data sent as content type application/json which is the default for $http .

However you are changing the default content type to application/x-www-form-urlencoded

If you want the $http to stay the same you need to use $_POST not file_get_contents()

If you want the php to stay the same you need to remove the content type header from $http and not use $.param to serialize the data.

Also note that if you want to redirect to checkout.php after the ajax the redirect won't contain the post data so you would need to store that in session to make this work. Otherwise you probably don't need $http at all and should just use browser to submit the form and not intercept to send with $http

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM