Marshall
Marshall

Reputation: 156

How can I use Angular $http to POST data to PHP

plenty of topics regarding this and I promise I have tried a lot (all day).

Here is the code I have:

app.controller('contactsController', function($scope, $rootScope, dataService, $http) {

        $rootScope.currentPage = "contact";

        $scope.postData = [];

        $scope.runScript = function() {
            $http({
                url: "post.php",
                method: "POST",
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                data: $.param({postData:$scope.postData})
            }).success(function(data, status, headers, config) {
                $scope.data = data;
            }).error(function(data, status, headers, config) {
                $scope.status = status;
            });

        };
    });
<form name="contactForm" method="post" ng-submit="runScript()">
            <div class="col-sm-10">
                <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">E-mail Address</span>
                    <input ng-model="{{postData.email}}" name="email" class="form-control" placeholder="[email protected]" aria-describedby="basic-addon1" required>
                </div>
            <br>
                <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">Message</span>
                    <textarea ng-model="{{postData.message}}" name="inputMessage" class="form-control"></textarea>
                </div>
            </div>
            <div class="col-sm-2">
                <button type="submit" class="btn btn-default">Send</button>
            </div>
        </form>
        {{data}} and {{status}}

$inputData = file_get_contents("php://input");

$inputData = json_decode($inputData);

$email = $inputData->email;

echo $email;

Now I've probably made a few mistakes whilst trying to get this to work, from what I had earlier - I'm not getting any errors but I'm also not getting any success - I've been at this all day!!!! Thanks!

Upvotes: 0

Views: 97

Answers (2)

Vittorio Delsignore
Vittorio Delsignore

Reputation: 36

I might be wrong but if you only use POST you should find your data in the _POST variable. You need to use file_get_contents("php://input") only if you submit PUT requests.

Also, you are submitting a key postData and you are trying to read ->email..

Upvotes: 0

Bas Slats
Bas Slats

Reputation: 277

Angular posts the data in JSON format that php does not natively consumes. You will have to read and json decode the input like so:

// get the raw POST data
$inputData = file_get_contents("php://input");

// this returns null if not valid json
$inputData = json_decode($inputData);

Upvotes: 1

Related Questions