0

I'm trying to send ajax request with username and password through Angularjs to Symfony but the I can't access the post variables. Here is my code:

HTML:

<div>
                        <input type="text" 
                        class="form-control defaultPassword" 
                        ng-model="username" 
                        placeholder="username">
                    </div>
                    <div class="form-group">
                        <input type="password" 
                        ng-model="password" 
                        class="form-control {% verbatim %}{{ passwordBox }}{% endverbatim %}" 
                        placeholder="password">
                    </div>
                    <div>
                        <span>{% verbatim %}{{ message }}{% endverbatim %}</span>
                        <button id="submitBtn" class="btn" ng-click="login()">login</button>
                    </div>

AngularController

todoApp.controller("LoginController", 
function LoginController($scope, $http){

    $scope.username = "";
    $scope.password = "";

    $scope.login = Login;

    function Login(){
        $http({
            method: 'POST',
            url: '/api/login',
            data: {
                username: $scope.username,
                password: $scope.password
            },
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).then(function successCallback(response) {
            console.log(response);
          }, function errorCallback(response) {
            alert("error");
          });;
    }

});

And here is the symfony controller:

/**
 * @Route("/api/login")
 * @Method("POST")
 */
public function apiLogin(Request $request){
    $us = $request->request->get("username");        
}

This method of retrieving the data doesnt work. I can see that the username and password are being sent but i have no access to them. Can you help me to find another way to get them in the symfony controller?

snaksa
  • 448
  • 1
  • 5
  • 15
  • 1
    Possible duplicate of [How do I POST urlencoded form data with $http in AngularJS?](http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs). The [second answer](http://stackoverflow.com/a/30970229/283366) is the better option – Phil Jun 10 '16 at 00:30

1 Answers1

0

Angular

$http({
    method  : 'POST',
    url     : url,
    headers : {'Content-Type': 'application/x-www-form-urlencoded'},
    data    : JSON.stringify(dataObj)
})
.success(function()
{
    console.error("Done");
})
.error(function(dataObj)
{
    console.error("Error");
});

Symfony

Include:

use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;

Function:

/**
  * POST Route annotation.
  * @Post("/api/login")
  */
    public function apiLoginAction(Request $request)
    {
        $parameters = $request->request->all();