Ajax-post: 400 Bad request: Missing required parameters

I was happy that Yii seemed to be quite intelligent with my ajax calls. But then I realized that I have forgotten to declare method:‘POST’. After adding this the calls produce the Bad Request error.

Is this wrong?


        

$.ajax({

  contentType: 'application/json; charset=utf-8',

  dataType: 'json',

  method: 'POST',

  url: '/some-other/do',

  data: {

    'itemId': itemId,

    'languageId': languageId,

    'newValue': newValue

  },

  success: function (data) {

    alert('success')

  },

  error: function (data) {

    alert('error');

  }

});

After searching a while I thought I had to add those csrf things, which I don’t know much about. So I added to data


'csrf-param':yii.getCsrfParam(),

'csrf-token':yii.getCsrfToken(),

But this didn’t help. And I guess this is not the current way of doing it in Yii2-beta since the csrf is passed by the cookie, right?

The action that gets called has these params:




public function actionDo($itemId, languageId, $newValue) {

    ...

}



Is this not possible or am I doing anything wrong? Is there not so much magic in Yii2? It works with method:‘GET’ but not with ‘POST’.

Can you open some sort of dev tools, and post the sent and received HTTP headers perhaps?

So, do you think it should work actually?

I have got the headers with ‘Live HTTP headers’ in Firefox. The URL and the values differ a bit from the posted code - I simplified it for readibility.


http://pim.localhost/localized-property-value/save-draft-value


POST /localized-property-value/save-draft-value HTTP/1.1

Host: pim.localhost

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:32.0) Gecko/20100101 Firefox/32.0

Accept: application/json, text/javascript, */*; q=0.01

Accept-Language: de,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

X-CSRF-Token: WGhtUmQuWEUUWxQoVWwsEBwEHxgGXQAoGw4rFBVkLQlgXCpjNE1gGg==

Content-Type: application/x-www-form-urlencoded; charset=UTF-8

X-Requested-With: XMLHttpRequest

Referer: http://pim.localhost/item/edit-master-localization?id=16

Content-Length: 147

Cookie: _csrf=b324a83e8db9aa196d893aeb2e1de6e508b94547bf35ea7baba075afd8a7d48ds%3A32%3A%22L3yz1BtUDlrJbsXmCfFFqJuL84G1Pc8_%22%3B; PHPSESSID=es15av5iovuahj2h7q5uuj2fv0

Connection: keep-alive

Pragma: no-cache

Cache-Control: no-cache

csrf-param=_csrf&csrf-token=WGhtUmQuWEUUWxQoVWwsEBwEHxgGXQAoGw4rFBVkLQlgXCpjNE1gGg%3D%3D&itemId=16&languageId=1&propertyDefinitionId=9&newValue=xxx


HTTP/1.1 400 Bad Request

Date: Mon, 13 Oct 2014 06:27:32 GMT

Server: Apache/2.4.10 (Fedora) PHP/5.5.17 Phusion_Passenger/4.0.42

X-Powered-By: PHP/5.5.17

Content-Length: 99

Connection: close

Content-Type: text/html; charset=UTF-8

----------------------------------------------------------



What does this tell you?

You are posting to a method which require parameters. url should be /some-other/do?id=x or whatever