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 Oct 19, 2016 at 9:48
  • @Rakesh I updated my question Oct 19, 2016 at 9:51
  • inside controller have you print anything? Oct 19, 2016 at 9:54
  • @Rakesh when i run the url its going 404 Oct 19, 2016 at 9:55
  • plz show your url string for me now 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
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? Oct 19, 2016 at 10:25
  • @DeebanBabu added the json array code.. 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.