Home > Mobile >  Magento Module Ajax Request Returning 404 Error
Magento Module Ajax Request Returning 404 Error

Time:06-22

I'm facing an issue with my Magento Module. It is working well on localhost, however when uploaded to the server, any Ajax request made returns a 404 error. I have created a Magento 2 Module in the Namespace Emps_MAMIntegration. I have also created a routes.xml file in etc/frontend/routes.xml with the following content.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="mamform" id="mamform">
            <module name="EMPS_MAMIntegration" />
        </route>
    </router>
</config>

In my template file, I'm making an ajax request to a file Controller/Index/Number.php as follows:

 $.ajax({
          url: '<?= $block->getUrl('mamform/index/number') ?>',
          type: 'POST',
          data: {
               type: 'model',
               make: make
           },
           success: function(data) {
              // handle success
            },
           error: function(error) {
                    // error handling
           }
 });

Then in my Number.php file:

<?php

namespace Emps\MAMIntegration\Controller\Index;

use Magento\Framework\Controller\Result\JsonFactory;
use EMPS\MAMIntegration\Helper\MamService;


class Number extends \Magento\Framework\App\Action\Action
{
    private $mamService;
    private $resultJsonFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        MamService $_mamService,
        JsonFactory $resultJsonFactory

    ) {

        $this->mamService = $_mamService;
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
    }

    public function execute()
    {


        $post = $this->getRequest()->getPostValue();
        // var_dump($post);
        if (!$post) {
            $this->_redirect($this->getRequest()->getServer('HTTP_REFERER'));
            return;
        }

        $resultJson = $this->resultJsonFactory->create();
        $type = $post['type'];

       /// omitted for brevity
      return $resultJson->setData(['models' => $data]);

    }
}

On localhost, all ajax request work as expected, and returns all data. However when I upload the module to the production environment, they fail with Error 404.

CodePudding user response:

Magento's routing might be case sensitive depending on server configuration

Your module name is EMPS_MAMIntegration but your namespace is Emps\MAMIntegration. I would bet on this being the reason for it working on some environment and not the other.

Try renaming your module to Emps_MAMIntegration or show us your register.php file. Also make sure module is enabled on production.

  • Related