Magento 2 — How to enable POST request on Controller without X-Requested-With: XMLHttpRequest

By Default, if you want to request thru post method, you need to need to decide this on Header Request :

X-Requested-With: XMLHttpRequest

Problem here is, what if we won’t include that header?

Use this classes by putting on top of class

use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Request\InvalidRequestException;

Impletements this interface to the controller :

class Paymentflag extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface

Edit your Controller by adding this methods to allow that request :

public function createCsrfValidationException(RequestInterface $request): ? InvalidRequestException
return null;

public function validateForCsrf(RequestInterface $request): ?bool
return true;

Go get the request without header.

I wrote these tutorials for myself in future when I forget for the next steps.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store