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;
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:
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 thecomponents
array:Then in your controller use this to get the JSON parameters:
I'm a newbie.. But I also want use checkboxcoloumns in gridview (Kartik version). 1st thing.
Instead of writing
I have to write
2nd thing. In the controller you can process the keylist, but don't try to decode it, simple use it int this way:
and it seems it works for me!
Sorry for my english..