0

I'm running phpcs which is code sniffer for magento 2. and I got this error from it :

 ERROR | Use of echo language construct is discouraged.
 ERROR | Use of die language construct is discouraged. 

When I looked into the code I found that the class controller has echo and die like this :

public function execute()
    {
        $json_encode = array();
        $itemId = (int)$this->getRequest()->getParam('item_id');
        $error = 0; $msg_error = "";
        try {
            $this->sidebar->checkQuoteItem($itemId);
            $this->sidebar->removeQuoteItem($itemId);
            $json_encode["sub_total_html"] = $this->_blockCart->renderTotals();
            $json_encode["items_count"] = $this->_blockCart->getQuote()->getItemsCount();

            /* render Order Total block on checkout/cart  */
            $grand_total = $this->_blockCart->displayBaseGrandtotal();
            $json_encode["grand_total_html"] = $this->_layoutFactory->create()
                        ->createBlock('Magento\Checkout\Block\Cart\Totals')
                        ->setData('grand_total', $grand_total)
                        ->setTemplate('Cmsmart_Ajaxcart::module-checkout/cart/totals/grand-total.phtml')
                        ->toHtml();

            /* return $this->jsonResponse(); */
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $error = 1;
            $msg_error = $e->getMessage();
           /*  return $this->jsonResponse($e->getMessage()); */
        } catch (\Exception $e) {
            $error = 1;
            $msg_error = $e->getMessage();
            /* $this->logger->critical($e);
            return $this->jsonResponse($e->getMessage()); */
        }
        $json_encode["error"] = $error;
        $json_encode["error_msg"] = $msg_error;
        echo json_encode($json_encode);
        die;
    }

I found somewhere that to replace echo and die use setBody() so I changed it the code above replacing echo and die like this :

$this->getResponse()
    ->clearHeaders()
    ->setHeader('Content-Type', 'application/json')
    ->setBody($json_encode);

This is solution from this link

But it breaks the behavior in the front-end because I'm using Ajax. Any idea ? I also added exit at the of the setBody() but still it freezing.

Note that this code is snippet from cmsmart

1 Answer 1

2

Use JsonFactory class like below:

public function __construct(
    ---     
    \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ---
) {
    ---
    $this->resultJsonFactory        = $resultJsonFactory;
    ---
}


public function execute(){
----
    $jsonResult = $this->resultJsonFactory->create();
    $jsonResult->setData($json_encode);
    return $jsonResult;
}

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.