Vitalii Isaenko Vitalii Isaenko - 1 year ago 192
Ajax Question

How to get data in controller's method via ajax?

I try asynchronously send data to controller's method. I suppose that's trivial challenge but did't fint the answer in SO.
Here is my code:


public function actionRaiting(string $idUser, string $idBook, int $number )
$model = new Raiting();
$model->idBook = $idBook;
$model->idUser = $idUser;
$model->number = $number;
if (\Yii::$app->request->isAjax)
if ($model->load(\Yii::$app->request->post()))


$('.rating-input i').click(function()
url: 'raiting',
type: "POST",
contentType: 'application/json',
data: {
idUser: $('[name=idUser]').val(),
idBook: $('[name=idBook]').val(),
number: $(this).data("value") ,
dataType : 'json'

I get the 400 error "not specified the required parameters".
Could you explain how should I do it? Thanks a lot!

Answer Source

Your method expects the values as GET parameters. You are passing them in the POST body. Normally I would suggest appending the parameters to the url.

However, since you are saving data to a database, which should be done via POST, I suggest you remove the parameters from your function. Any validation to be done should be done in your model before the saving.

public function actionRaiting() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download