Within the context of my project, I am making an xhr request to a yii2 controller.
Here is how the request is structured in my view:
var xhr = new XMLHttpRequest();
xhr.open('POST', '$urlToController', true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
};
// Output on console first
console.log({ id: JSON.stringify($('#grid').yiiGridView('getSelectedRows')), _csrf : csrfToken});
xhr.send({ id: JSON.stringify($('#grid').yiiGridView('getSelectedRows')), _csrf : csrfToken}});
And here is my controller:
public function actionTargetController() {
if(Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
if (Yii::$app->request->isPost) {
$post = Yii::$app->request->post();
return $post; // Print out $post
}
}
}
However, when I attempt to send the data using xhr.send()
, I do not receive any response in the yii2 controller and the result is always '[]' (empty array).
I have also attempted to send the data using the FormData Object with the same outcome.
Where could I be going wrong? Thank you in advance for your assistance.
PS:
The _csrf parameter is not being passed either, so I have disabled csrf validation in the beforeAction method.