7

I want to call this controller through Ajax and have it return true or false. the methods all work correctly, however I get the error

Invalid return type C:\Sites\retracted\wwwroot\vendor\magento\framework\App\Bootstrap.php(258): Magento\Framework\App\Http->launch()

So I assume with extends Action I can't simply return a boolean - but what should it be to allow me to return a bool?

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

class IsEmailRegistered extends Action implements \Magento\Framework\DataObject\IdentityInterface
{

    ...

    public function execute()
    {
        $result = $this->voucherHelper->validateEmail($email);

        return $result;
    }
}

1 Answer 1

12

Try this example:

protected $resultJsonFactory;

/**
 * @param Context $context
 * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
 */
public function __construct(
    Context $context,
    \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
)
{
    $this->resultJsonFactory = $resultJsonFactory;
    parent::__construct($context);
}

/**
 * Collect relations data
 *
 * @return \Magento\Framework\Controller\Result\Json
 */
public function execute()
{
    $result = $this->voucherHelper->validateEmail($email);
    /** @var \Magento\Framework\Controller\Result\Json $result */
    $resultJson = $this->resultJsonFactory->create();

    return $resultJson->setData(['success' => $result]);
}

But in your code you should parse the answer as JSON.

1
  • That gave an error because it couldn't find the JsonFactory class, but corrected that and edited your answer for anyone else looking in the future. Other than that, worked perfectly :)
    – tim.baker
    Sep 8, 2016 at 12:27

Your Answer

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

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