Error in accessing post json data in yii2

Geoff picture Geoff · Aug 5, 2016 · Viewed 10.7k times · Source

Am passing data to yii2 using ajax request but i keep on getting a 500 error

This is the ajax request code:

<?php 
 $script = <<< JS

     $('form#forward_pr').on('beforeSubmit', function(e){
    var keys = $('#grid').yiiGridView('getSelectedRows');
     $.post({
       url: "forwardpr", // your controller action
       dataType: 'json',
       data: {keylist: keys},
       success: function(data) {
          alert('I did it! Processed checked rows.')
       },
     error: function(err){
       console.log("server error");
       }
    });
       return false;
    }  ) ;

    JS;
    $this->registerJS($script);
 ?>

When i do console.log(keys) this returns

[0, 1]

This is my controller code:

if (Yii::$app->request->post()) {
         echo $post = json_encode($_POST['keys']);
          if (isset($_POST['keylist'])) {
                $keys = \yii\helpers\Json::decode($_POST['keylist']);
              print_r($keys);
            }else{
              echo "1";
          }

The above always executes the error part of post request, What could be wrong;

Answer

jlapoutre picture jlapoutre · Aug 8, 2016

You are sending your JSON as encoded (post) data body, not key value pairs. So your approach is not working this way.

There are two options to fix this:

  1. refactor your controller into a RESTful service
  2. in your controller use the JSON body rather than POST parameters

While the first option is preferred in the long run, the second option is pretty simple as a quick fix.

First, make sure you configure your app to parse JSON body conten. IN config.php add this to the components array:

'request' => [
    'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ]
]

Then in your controller use this to get the JSON parameters:

$model->load(Yii::$app->getRequest()->getBodyParams());