简体   繁体   中英

Angular's $http.post to PHP empty $_POST

I have the following scenario, I have an Angular variable called contact which is a JSON object that has the following members:

  • Message
  • Name
  • Phone
  • Email

I console.log(contact) and it logs the correct information, however once sent, $_POST['contact'] results in an empty array. I was reading around and found that $_POST['contact'] won't get populated like it would if it were an http request from jQuery. So I fixed it to the following:

$params = json_decode(file_get_contents('php://input'),true);
print_r($params);

And here is the Angular function:

$scope.submitForm = function(contact){
        console.log(contact);
        $scope.clearContactFormData();
        return $http.post('http://localhost/cpr_courses/app/methods/contact.php', contact).success(function(data){
            Materialize.toast(data, 4000);
        });
    }

Still the print_r($params) is empty. I have no idea what else is going on. Any help please?

EDIT

console.log() outputs the following:

Array[0]
email
:
"asd@asd.asd"
length
:
0
message
:
"rubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOBrubAWREIUVBAERWOBNATEIOB"
name
:
"rubAWREIUVBAERWOBNATEIOB"
phone
:
"13345678"

and here is the network tab image:

响应头

Here's the declaration of the JSON object:

$scope.contact = {};
$scope.onlyNumbers = /^[0-9]+$/;

This is later put on on the form like this:

<form method="post" class="form-sl" role="form" name="contactForm" ng-submit="submitForm(contact)" novalidate enctype="multipart/form-data">

and later on, on each field like this:

<input type="email" name="email" id="email" ng-model="contact.email" autocomplete="off" ng-maxlength="50" length="50" required/>

Is that okay?

The $_POST superglobal is a PHP commodity to automatically decode the body of the typical POST request sent by HTML forms. In other words, it expects one of these values in the Content-Type request header:

  • application/x-www-form-urlencoded
  • multipart/form-data

Since you have application/json , it remains empty.

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