0

I've created a controller within my custom module to add items to my basket and i'm trying to make an ajax call across to it. However, I can't even call my controller currently as I get a 404 error from my ajax call.

This is how my Controller currently looks:

<?php

namespace Vendor\TestModule\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Test extends Action
{

    public function __construct(
        Context $context
    ) {
        parent::__construct($context);
    }

    public function execute()
    {
        return "Success";
    }
}

This is the ajax call in my phtml file:

var data = "";
var addToCartUrl = "<?php echo $block->getUrl('testmodule/index/test'); ?>";

$.ajax({
    url : addToCartUrl,
    dataType : 'json',
    type : 'POST',
    data: data,
    success : function(res)
    {
        console.log('Success');
    },
    error : function()
    {
        console.log('error');
    }
});

Here is my routes.xml file:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
    <route id="test_testmodule" frontName="test_testmodule">
        <module name="Test_TestModule" />
    </route>
</router>

I've tried to manually visit the URL that i'm sending the ajax call to and that doesn't display anything either.

10
  • how did you define the route for this controller?
    – Diana
    Commented Feb 11, 2021 at 12:27
  • @DianaBotean I will add it to the question 1 sec Commented Feb 11, 2021 at 12:28
  • please try test_testmodule/index/test in call url
    – Pawan
    Commented Feb 11, 2021 at 12:38
  • shouldn't you use then 'test_testmodule' in the url (as this is your frontName)?
    – Diana
    Commented Feb 11, 2021 at 12:39
  • 2
    oh and also, i think you should use the 'standard' router id and not 'admin' if you are working on the frontend side as per your url call
    – Diana
    Commented Feb 11, 2021 at 12:44

1 Answer 1

1

as discussed, i see that a few corrections are needed:

  1. you should call the 'test_testmodule/index/test' url as you defined your frontName as 'test_testmodule'
  2. you should use the 'standard' routerId if you are working on the frontend side with this call
  3. you are expecting a JSON formatted response as per your AJAX call definition, so you will have to format it serverside by injecting Magento\Framework\Controller\Result\JsonFactory into a protected property (say $resultJsonFactory) inside your controller class and using it like so:
$result = $this->resultJsonFactory->create();
return $result->setData(['success' => true]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.