Home ajax post data is not read yii2
Reply: 1

ajax post data is not read yii2

AMS - ovic
1#
AMS - ovic Published in 2017-12-07 21:03:23Z

I'm trying to read $_POST array posted through AJAX in a controller action using Yii::$app->request->post(), but something strange happens.

jQuery: `

    function renderGridView() {
    var formId = $('#input-field :input[value!=""]');
    // extract values. Make sure to send _csrf token

   $.ajax({
       url: "?r=value-search%2Fsearch", //this one works
       method: 'POST',
       data: {
           searchData: formId.serializeArray(),
       },
       success: function(response) { //JSON array is returned. 
           /*$('#resultGrid').DataTable( {
               data: [
                   response['provider']
                ],
               columns: [
                   response['columns']
                ]
           }); */
           console.log(response);

       }


   })

}

`

PHP Controller action:

public function actionSearch() {
       $data = \Yii::$app->request->post('searchData');
       $tt; $svalue;
       if(count($data) === 0) {throw new UserException('data is emptry');}

       echo var_dump($data);
    }

And here's the issue, the code above works just fine. But when I'm trying to echo $data my custom UserException 'data is empty' is thrown, instead of PHP's 'trying to pass array as a string', which I'd normally expect. What is causing this? Why does post() behave like this? Is there a technical reason to it?

Muhammad Omer Aslam
2#
Muhammad Omer Aslam Reply to 2017-12-07 21:29:29Z

just change

 data: {
           searchData: formId.serializeArray(),
       },

to

 data:formId.serialize(),

you should use ActiveForm to create your form using your model and the names will be automatically assigned to inputs which include the convention ModelName[field_name] apart from this you haven't shown your form but in your action you are getting the searchData in the post() array so I assume you have the data being posted as

[
  searchData=>[
    field_1=>value,
    field_1=>value,
    field_1=>value,
    field_1=>value,
  ]
]
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.326968 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO