Answer the question
In order to leave comments, you need to log in
How to make an ajax request in Magento 2.4?
It is necessary to execute an ajax request from the product page. The Internet is full of examples of how to do this for older versions of Magento, there are options from my custom page, I try by analogy, it doesn’t work - if through the address bar of the browser - everything works, if from javascript - no. The controller's constructor fires, but the execute() method is not called, ajax itself returns with a 302 status, after which the product page is called again
$.ajax({
url: baseUrl + 'module/ajax/fooaction',
type: "POST",
data: {},
showLoader: true,
cache: false,
crossDomain:true,
dataType: 'json',
success: function(response){
}
});
<?php
namespace Vendor\Module\Controller\Ajax;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\Action\HttpGetActionInterface;
class FooAction implements HttpGetActionInterface
{
/**
* @var \Magento\Framework\App\Action\Contex
*/
private $context;
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
*/
public function __construct(Context $context, JsonFactory $resultJsonFactory)
{
$this->context = $context;
$this->resultJsonFactory = $resultJsonFactory;
}
/**
* @return json
*/
public function execute()
{
$params = $this->context->getRequest()->getParams();
$resultJson = $this->resultJsonFactory->create();
$resultJson->setData(['message' => 'Hello world', 'success' => true]);
return $resultJson;
}
}
...............
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\Action\Action;
class FooAction extends Action implements HttpGetActionInterface, HttpPostActionInterface
{
/**
* @var \Magento\Framework\App\Action\Contex
*/
private $context;
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
*/
public function __construct(Context $context, JsonFactory $resultJsonFactory)
{
$this->context = $context;
$this->resultJsonFactory = $resultJsonFactory;
parent::__construct($context);
}
............................................................
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="module" frontName="module">
<module name="Vendor_module" />
</route>
</router>
</config>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question