The goal is to post to an action using AJAX from a foreign domain.
Here is the error:
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
You need specifically allow other domains to access your actions through AJAX and also allow POST method. Add the following to the Controller in question:
- public function beforeAction($action)
- {
- $this->enableCsrfValidation = false;
- header("access-control-allow-origin: *");
- header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
- header("Access-Control-Allow-Headers: Content-Type");
- if (!parent::beforeAction($action)) {
- return false;
- }
- return true;
- }
Notice that to receive POST data you need disabled Csrf verification. The Csrf system will not work in this scenario.