Yii2 and AngularJs Post

Hi,

I have set up a simple ajax request system in yii2.

For simple GET ajax there is no problem, event with Yii2 CSRF Validation.

But when I try to use the POST, Yii2 controller reply empty post data (and there are data sent by POST)

Here is sample of Code :





// For Initialisation

    sidebar.config(function ($httpProvider) {

        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

        $httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';


    });


    sidebar.run(function run($http) {

        var _csrfAngular = angular.element('#_csrfAngular').val();

        $http.defaults.headers.post['X-CSRF-Token'] = _csrfAngular;

    });


// End of Init

// When search is requested then :

        $scope.searchIndications = function () {


            var indicationsIds = [];

            for (var i = 0; i < $scope.selectedCategories.length; i++) {

                indicationsIds.push($scope.selectedCategories[i].id);

            }


            var req = {

                method: 'POST',

                url: '/panel/indications/getIndications',

                data: {IDs: 25,toto:'hello'}


            };


            $http(req).success(function (data) {

                $scope.proposedIndications = data;

                $scope.selectedIndications = [];

                // always return empty data

                console.debug(data);

            });

        };



In Controller :




    public function actionGetIndications() {


        $request = Yii::$app->request;


        if ( Yii::$app->user->isGuest ) {


            return 'No Comment';

        }

        if ($request->isAjax) {


            // Found Indications retreiving by Categories

            $request = Yii::$app->request;


            // must be an Array

            $categoriesID = $request->post('IDs');


// Just to know whether Yii2 recognize sent POST data

            print_r($request->post());

            die();


            $query = new Query();

            $query->select('indication.id as ind_id, indication.name as ind_name');

            $query->from('indication_category');

            $query->leftJoin('indication', 'indication.id = indication_category.indication_id');


            $query->where(['category_id'=>$categoriesID]);


            $indications = $query->distinct()->all();


            return json_encode($indications);

        }

        else return json_encode(['not ajax'=>1]);

    }



It seems that Yii2 is unable to collect the POST

Here is the Http debug :




Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0

Connection:Keep-Alive

Content-Length:21

Content-Type:text/html

Date:Mon, 23 Mar 2015 12:32:05 GMT

Expires:Thu, 19 Nov 1981 08:52:00 GMT

Keep-Alive:timeout=5, max=89

Pragma:no-cache

Server:Apache/2.4.9 (Win64) PHP/5.5.12

Set-Cookie:PHPSESSID=s2eb8i37da7eh44ad5s078r0f2; path=/; HttpOnly

X-Powered-By:PHP/5.5.12

Request Headers

view source

Accept:application/json, text/plain, */*

Accept-Encoding:gzip, deflate

Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,cs;q=0.2,de;q=0.2,es;q=0.2,gl;q=0.2,it;q=0.2,nb;q=0.2,nl;q=0.2,pt;q=0.2,sv;q=0.2

Cache-Control:no-cache

Connection:keep-alive

Content-Length:25

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

Cookie:__ngDebug=true; _csrf=9ab0a80e7b69934246eea2f1e0249f8229a09ed48b7738ae5ecd5eb368e45a72s%3A32%3A%228_GgaT8uPdxUIvzLvtKEGwndwBZbB_p7%22%3B; _identity=582e362ce3be67fc7de173cfb5a66c81aef99b96b547b1268d197945109c8f13s%3A43%3A%22%5B3%2C%224V8JvvGZwcwDdLyF56d3nJLoom5Md4_p%22%2C3600%5D%22%3B; PHPSESSID=s2eb8i37da7eh44ad5s078r0f2

Host:naturo.dev

Origin:http://naturo.dev

Pragma:no-cache

Referer:http://naturo.dev/panel/indications

User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36

X-CSRF-Token:TmdDdFNNWkN2OAQTMhliNh4DOyEaOyAPOBMIMRQ6NCc5JRkWERIqdA==

X-Requested-With:XMLHttpRequest

Form Data

view source

view URL encoded

{"IDs":25,"toto":"hello"}:



To precise:

When I do it with a simple jQuery post request, then it works as a charm




$(document).ready(function () {

    $.ajax({

        type: "POST",

        url: '/panel/indications/getIndications',

        data: { IDs: 2}

    }).done(function(data){

        console.debug(data)

    });


});



Seems also strange due to I do not mention CSRF in the jQuery request.

But looking at debug, the CSRF token is added to jQuery request header.

When in Php i sent in response the value of $_POST then I get empty data for the request made with Angular.

And I get the real data for the request sent with jQuery…

Do you have an idea ?

Something real strange.

When I look at the Request Yii2 code and debug then




$this->getRawBody();  //from web\Request give me the good value of $_POST

$this->getBodyParams(); //from web\Request give me empty value ... 



So when I send back from controller : $this->getRawBody() I get the data, when I use $this->getBodyParams(); I get … nothing.

Is there a Yii2 bug ?

I get all informations if I do like this :




    public function actionGetIndications() {


        $request = Yii::$app->request;


        if ( Yii::$app->user->isGuest ) {


            return 'No Comment';

        }

        if ($request->isAjax) {


            // Found Indications retreiving by Categories

            $request = Yii::$app->request;


            $data =  json_decode(utf8_encode(file_get_contents("php://input")), false);

            return json_encode(['indic'=>'ok','postData'=>$data]);


        }

        else return json_encode(['not ajax'=>1]);

    }



OK guys.

It is JUST the way to manage POST coming from AngularJS.

Disgusted !!!

I think this is the proper way to do this:




// @app/config/web.php

'components' => [

        'request' => [

            'cookieValidationKey' => 'somekey',

            'parsers' => [

                'application/json' => 'yii\web\JsonParser', // required for POST input via `php://input`

            ]

        ],

        ...

],



yes, I’ve tried several ways, but I’ve tried and main configurations with it and succeeded, thanks