Ajax request form from validate from controller in magento 2 to avoid XSS attack

From Key Load:

<?php
    //-- form key load
    echo $this->getBlockHtml('formkey');
?>

 

AJax Request

var formKey = jQuery("[name='form_key']").val();
jQuery.ajax({
    url: "<?php echo $baseUrl.'testing/test/index';?>",
    type: "POST",
    data: {form_key:formKey},
    success: function(response){
        try {
        console.log(response);

        }catch(err) {}
    }
});

 

Controller Code:

<?php
namespace Equaltrue\Themeoption\Controller\Taxmode;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\App\ObjectManager;

class Index extends \Magento\Framework\App\Action\Action
{

    /**
     * @var Validator
     */
    private $formKeyValidator;

    /**
     * @param Context $context
     * @param Validator $formKeyValidator
     */
    public function __construct(
        Context $context,
        Validator $formKeyValidator = null
    )
    {
        $this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class);
        parent::__construct($context);
    }

    public function execute()
    {
        if ($this->getRequest()->isPost() && $this->isAjax() && $this->formKeyValidator->validate($this->getRequest())) {
            echo "this post & ajax & valid request.";
        }
    }

    /*
     *  Check Request is Ajax or not
     * @return boolean
     * */
    protected function isAjax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
    }
}

 

Was this article helpful?

Related Articles

Leave A Comment?