AJAX access control

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:

  1. public function beforeAction($action)
  2. {
  3.     $this->enableCsrfValidation = false;
  4.     header("access-control-allow-origin: *");
  5.     header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
  6.     header("Access-Control-Allow-Headers: Content-Type");
  7.  
  8.     if (!parent::beforeAction($action)) {
  9.         return false;
  10.     }
  11.  
  12.     return true;
  13. }

Notice that to receive POST data you need disabled Csrf verification. The Csrf system will not work in this scenario.

Published by

Joel Bowers

Web developer since 1999. PHP, YII2, Laravel, Javascript, HTML, CSS, jQuery, Perl, Wordpress, MySQL.

Leave a Reply

Your email address will not be published. Required fields are marked *