It is necessary to transfer an array of idshnik using AJAX in php , but error 400 comes out of the console (wrong parameters)

I wrote this code on js :

  var xhr = new XMLHttpRequest(); var body = JSON.stringify({ id: checkedInputTagsArray //массив идшников }); console.log(body); xhr.open('POST', '/products/' + action , true); //action - ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8'); xhr.send(body); 

php code:

  $request = Yii::$app->request; if (!$request->isAjax) { return "not ajax"; } $json = json_encode($request->getBodyParams()); return $json; 

Yes, it does nothing, but I would first establish a connection and see if the data is being transmitted.

Is there any difference between open(..., /model/action) and open(..., http://host/model/action) ? Just with my host, my debugger does not display Ajax requests ...

  • Make sure you pass crf token for more details here: stackoverflow.com/a/27126356/7678419 - Sergey-N13
  • @SergeyN, yes, now the request reaches the server, but the server returns only 500 errors. - dasauser
  • Now you have an error on the server side :) Try replacing json_encode with json_decode because the encode function converts the object into a JSON string, and you need to do the opposite - Sergey-N13
  • @SergeyN, yes, exactly, mixed up. thank. but I can't figure out how to accept the data and return it for viewing? - dasauser
  • If you want to do just return the data that is sent to the server, use this example: stackoverflow.com/a/41675108/7678419 - Sergey-N13

1 answer 1

it was necessary to disable csrf validation and add Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; in the appropriate action