Asked  7 Months ago    Answers:  5   Viewed   37 times

I have a form with the tag ng-submit="login()

The function gets called fine in javascript.

function LoginForm($scope, $http)
{
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

    $scope.email    = "fsdg@sdf.com";
    $scope.password = "1234";

    $scope.login = function()
    {
        data = {
            'email' : $scope.email,
            'password' : $scope.password
        };

        $http.post('resources/curl.php', data)
        .success(function(data, status, headers, config)
        {
            console.log(status + ' - ' + data);
        })
        .error(function(data, status, headers, config)
        {
            console.log('error');
        });
    }
}

I am getting a 200 OK response back from the PHP file, however, the returned data is saying that email and password are undefined. This is all the php I have

<?php
$email = $_POST['email'];
$pass  = $_POST['password'];
echo $email;
?>

Any idea why I am getting undefined POST values?

EDIT

I wanted to point out since this seems to be a popular question (yet it is old), .success and .error have been deprecated and you should use .then as @James Gentes pointed out in the commments

 Answers

74

angularjs .post() defaults the Content-type header to application/json. You are overriding this to pass form-encoded data, however you are not changing your data value to pass an appropriate query string, so PHP is not populating $_POST as you expect.

My suggestion would be to just use the default angularjs setting of application/json as header, read the raw input in PHP, and then deserialize the JSON.

That can be achieved in PHP like this:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;

Alternately, if you are heavily relying on $_POST functionality, you can form a query string like email=someemail@email.com&password=somepassword and send that as data. Make sure that this query string is URL encoded. If manually built (as opposed to using something like jQuery.serialize()), Javascript's encodeURIComponent() should do the trick for you.

Wednesday, March 31, 2021
 
peixotorms
answered 7 Months ago
61

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

Saturday, May 29, 2021
 
DMTintner
answered 5 Months ago
99

Updated, this is code that was just tested with php and Apache - and it works. I also changed your server.php file like below. The file was created based on AngularJS Hub's Server Calls sample. The same source was used to create mainController.js' $http.post(...) method call so that it successfully posts data to the server.

Screenshot (after submit)

enter image description here

server.php

<?php
 if ($_SERVER["REQUEST_METHOD"] === "POST")
  {

   $result = "POST request received!";

  if (isset($_GET["name"]))
  {
    $result .= "nname = " . $_GET["name"];
  }

  if (isset($_GET["email"]))
  {
    $result .= "nemail = " . $_GET["email"];
  }

  if (isset($HTTP_RAW_POST_DATA))
  {
    $result .= "nPOST DATA: " . $HTTP_RAW_POST_DATA;
  }

  echo $result;
  }

?>

personForm.html

   <!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title></title>

    </head>
        <body ng-app="mainModule">
            <div ng-controller="mainController">
                <form name="personForm1" validate ng-submit="submit()">
                    <label for="name">First name:</label>
                    <input id="name" type="text" name="name" ng-model="person.name" required />
                    <br />
                    {{person.name}}
                    <br />
                    <label for="email">email:</label>
                    <input id="email" type="text" name="email" ng-model="person.email" required />
                    <br />
                    <br />
                    <button type="submit">Submit</button>
                </form>
                <br />
                <div>
                    {{serverResponse}}
                </div>
            </div>

            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
            <script src="mainController.js"></script>
            <!--<script type="text/javascript" src="script/parsley.js"></script>
            <script src="script.js"></script>-->
        </body>

</html>

mainController.js

angular.module("mainModule", [])
  .controller("mainController", function ($scope, $http)
  {
  $scope.person = {};

  $scope.serverResponse = "";

  $scope.submit = function ()
  {

      console.log("form submit");

      var params = {
          name: $scope.person.name,
          email: $scope.person.email
      };

      var config = {
          params: params
      };

      $http.post("server.php", $scope.person, config)
      .success(function (data, status, headers, config)
      {
          console.log("data " + data + ", status "+ status + ", headers "+ headers + ", config " + config);
          $scope.serverResponse = data;
          console.log($scope.serverResponse);
      })
      .error(function (data, status, headers, config)
      { console.log("error");
          $scope.serverResponse = "SUBMIT ERROR";


       });
      };
  });// JavaScript source code

Alternative way, with JSON handling:

server_json.php

<?php
  if ($_SERVER["REQUEST_METHOD"] === "POST")
  {
     /* code source: http://stackoverflow.com/a/22852178/2048391 */
     $data = array();
     $json = file_get_contents('php://input'); // read JSON from raw POST data

     if (!empty($json)) {
        $data = json_decode($json, true); // decode
     }

     print_r($data);

    }

  ?>

Screenshot (after submit)

Screenshot

Saturday, May 29, 2021
 
Lorav
answered 5 Months ago
58

You could set the key by index notation of array as you want to set user['token'] dynamically

Code

var formData = { email : email, password : password};

formData[user['token']] = token; //assuming user & token object has already defined

//user[token] : token

$http.post('http://api.myprivatebox.com/users.json', formData).then(function(results) {
    console.log('mid');
});
Saturday, May 29, 2021
 
LOKESH
answered 5 Months ago
28

Your request does not contain a URL parameter named "data", therefore request.getParameter("data") returns null and you get the NullPointerException.

You try to send a Javascript object via URL parameters which does not go well with non-shallow objects.

I would recommend to send the data as request payload:

JsonObject obj = (JsonObject) parser.parse(request.getReader());

On the client you need to make sure that your data is sent as proper JSON:

$http({
        method : 'POST',
        url : 'login',
        contentType: 'application/json',
        data : JSON.stringify($scope.user),
    })...
Tuesday, August 3, 2021
 
StampyCode
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :