I was trying to implement page caching in Yii2 advanced project and everything seemed to be super cool. And suddenly I was hit by a strange issue.
Case: On the homepage of the website there is some dynamic data like showing records from DB, info of current user like the name (if the user is logged-in) and some static content. Also, a search input field which fetches result using AJAX call.
To speed page loading I implemented PageCaching provided by Yii2. And all worked good. But one issue I got stuck at is that after user log-in the ajax call didn't work and gave Error:
Bad Request (#400): Unable to verify your data submission.
I get this error till cache is refreshed after the set duration or I disable cache.
Is this issue related to cookie/session or something else? How to resolve it?
The
400 Bad Requestis because thecsrf-tokenis not being sent, with the request which is required to prevent cross-site attacks by Yii whenever you usePOSTto submit a page or ajax request, if you create anActiveFormthen it creates an input automatically with the token value.You didn't add the code that you are using for the ajax call so not clear if you are using it for only one field or the whole form, so I would suggest the concerning part only.
You need to send the csrf-token and you can get it via javascript using
yii.jsand calling these 2 methodsyii.getCsrfParam()to get the parameter name of the tokenyii.getCsrfToken()to get the token or actual value of the csrf-tokenThe
csrfParamname is configured inside yourfrontend/config.phporconfig/web.phpdepending on the app you are using (advance /basic) under therequestcomponent like belowSo what you need to do is either change the request method from
POSTtoGETand send data via query string or use the following way to send thePOSTrequest.Note: You should change the URL and add the csrf data into your existing data that you are sending with the requestIf you have a
testaction inside theSiteControllerwith the following code, then the above ajax call should show you the$_POSTarray inside the console with the csrf param and token value askey=>value.