2

I am trying to create a custom controller in magento 2.1. I have created routes.xml and namespace as

routes.xml

 <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
        <router id="standard">
            <route id="customattribute" frontName="customattribute">
                <module name="Namespace_Modulename" />
            </route>
        </router>
    </config>

controller

namespace namespace\modulename\Controller\Searchajax;

    class Index extends \Magento\Framework\App\Action\Action
    {
        /**
         * say hello text
         */

         public function execute()
        {
            return 'Hello world!';
        }

    }

in my controller file. But I am not getting the required result. Please suggest to me a way to do this. Thanks in advance.

5
  • show your routes.xml code Commented Oct 19, 2016 at 9:48
  • @Rakesh I updated my question Commented Oct 19, 2016 at 9:51
  • inside controller have you print anything? Commented Oct 19, 2016 at 9:54
  • @Rakesh when i run the url its going 404 Commented Oct 19, 2016 at 9:55
  • plz show your url string for me now Commented Oct 19, 2016 at 9:57

2 Answers 2

2

You have to pass url like below,

<?php echo $this->getUrl('customattribute/searchajax/index'); ?>

Now inside your controller file, you can debug more inside execute function.

2
  • It returns 404 url Commented Oct 19, 2016 at 10:03
  • Have you used above url? Commented Oct 19, 2016 at 10:04
2

problem in xml xsi:noNamespaceSchemaLocation

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

controller code return the json array

namespace namespace\modulename\Controller\Searchajax;
use Magento\Framework\Controller\ResultFactory;

    class Index extends \Magento\Framework\App\Action\Action
    {
        /**
         * say hello text
         */

         public function execute()
        {
            $data=array('a','b','c');
            $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $resultJson->setData($data);
            return $resultJson;
        }

    }
2
  • How to return array in my controller? Commented Oct 19, 2016 at 10:25
  • @DeebanBabu added the json array code.. Commented Oct 19, 2016 at 10:29

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.