cancel
Showing results for 
Search instead for 
Did you mean: 

After making ajax query controller redirects back to product page

SOLVED

After making ajax query controller redirects back to product page

Hello!

 

I’m making an ajax query from a product page (code below). If I run it directly in browser, it works but if I run it inside a code (javascript) it redirects me back to the product page with a status 302 (picture attached).

 

It’s Magento 2.4.0.

 

How to make it work right so it won’t redirect me back to product page? Thanks in advance!

 

<?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;
    }
}

---------------------

                    $.ajax({
                        url: baseUrl + 'module/ajax/fooaction',
                        type: "POST",
                        data: {},
                        showLoader: true,
                        cache: false,
                        crossDomain:true,
                        dataType: 'json',
                        success: function(response){
                        }
                    });

2235235.PNG

1 ACCEPTED SOLUTION

Accepted Solutions

Re: After making ajax query controller redirects back to product page

SOLVED: It worked throught storage.post() ('mage/storage')

View solution in original post

2 REPLIES 2

Re: After making ajax query controller redirects back to product page

SOLVED: It worked throught storage.post() ('mage/storage')

Re: After making ajax query controller redirects back to product page

Hello @antoniogur615a 

 

You can also pass form key in ajax and check.
 
Thank you.
Problem solved? Click Kudos and "Accept as Solution".
200+ Magento 2 Extensions for Enhanced Shopping Experience.