0

In below program i got an error like Exception: Warning: Cannot modify header information - headers already sent in magento 2.I am not understand where i am writing wrong code.please help on this.

<?php
namespace Namespace\Modulename\Controller\Index;

class Addtocart extends \Magento\Framework\App\Action\Action {
protected $_resultPageFactory;
protected $product;
protected $customerSession;
protected $customer;
protected $jsonHelper;
protected $checkoutSession;
protected $cart;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Catalog\Model\Product $product,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\Json\Helper\Data $jsonHelper,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Checkout\Model\Cart $cart,
\Magento\Customer\Model\Customer $customer
) {
    $this->_resultPageFactory = $resultPageFactory;
$this->product = $product;
$this->customerSession = $customerSession;
$this->customer = $customer;
$this->jsonHelper = $jsonHelper;
$this->checkoutSession = $checkoutSession;
$this->cart = $cart;
    parent::__construct($context);

}
public function execute()
{
//echo "kdjhjkdh";die("here");
//        $this->_view->loadLayout();
//        $this->_view->renderLayout();
if(isset($_POST['q']))
    {
        $id = $_POST['q'];
    }
    $qty = 1;
try
{
    $product_id = $this->product->getIdBySku($id);
    $host = $_SERVER["HTTP_HOST"];
    $host =  explode(".",$host);
//      if(count($host) > 2)
//          {
//              $final_host = $host[0];
//              if($final_host != "www")
//              {
//                  $connection = Mage::getSingleton('core/resource');
//                  $read_connection = $connection->getConnection('core_read');   
//                  $collection_subdomain = Mage::getResourceModel('tricore_connectpro/subdomain_collection')->addFieldToSelect(array("id_subdomain","customer_id","directory_name"))->addFieldToFilter(array('directory_name'),array(array('eq' => $final_host)));
//                  $collection_data = $collection_subdomain->getData();
//                  $Customer_id = $collection_data[0]["customer_id"];
//                                              
//                  $read = Mage::getSingleton('core/resource')->getConnection('core_read');
//                  $result = $read->fetchAll("select * from `connectpro_social` where `customer_id` = '$Customer_id' ");   
//                  $ProductAll = $result[0]['show_all_product'];   
//                  
//                                        $val=json_decode($result[0]['product_ids'],TRUE);
//                                        $productidfromjson=call_user_func_array('array_merge',$val);
//                                        if($Customer_id != "" && !in_array($product_id,$productidfromjson)):  
//                      
//                      $res = array('result'=>'wrong_sku','cartQty'=>0);
//                      echo $result = json_encode($res);
//                      return;
//                      
//                  endif;  
//              }       
//          }
        $product = $this->product->load($product_id);
//      if ($this->customerSession->isLoggedIn())
//          {
//              $tri_customer_id = $this->customerSession->getCustomer()->getId();
//              $tri_customerData = $this->customer->load($tri_customer_id)->getData("metagenics_ok");  
//              if($tri_customerData == 0)
//              {
//                  $is_set_manufacture = $product->getData('manufacturer');
//                  if(!empty($is_set_manufacture) && strtolower($is_set_manufacture) == "metagenics")
//                  {
//                      $res = array('result'=>'cart_failure','cartQty'=>0);
//                      echo $result = $this->jsonHelper->jsonEncode($res);
//                      return;
//                  }
//              }
//          }
        $productType=$product->getTypeID(); 
        if($productType == 'simple')
        {
                            $updateId = 0;
                            //$session = Mage::getSingleton('core/session', array('name'=>'frontend'));
            //$cart = $this->cart->getCart();
                            foreach($this->cart->getQuote()->getAllItems() as $cartItem){
                                if($product->getSku() == $cartItem->getSku() && $cartItem->getParentItemId() == ""){
                                    $updateId = $cartItem->getId();
                                    $cartData=array($updateId=>array("qty"=>$cartItem->getQty()+1));
                                }
                            }
                            if($updateId == 0){
                                $this->cart->addProduct($product, $qty);
                            } else {
                                $cartData = $this->cart->suggestItemsQty($cartData);
                                $this->cart->updateItems($cartData);
                            }
            $this->checkoutSession->setLastAddedProductId($product->getId());
            $this->cart->save();
            $this->checkoutSession->setCartWasUpdated(true);
            $cartQtyRes = 'My Cart ('.$this->cart->getItemsQty().' items)';
            $res = array('result'=>'success', 'cartQty'=>$cartQtyRes);
        }
        else if($productType == 'configurable')
        {
            $res = array('result'=>'failure','cartQty'=>0);
        }
        else
        {
            $res = array('result'=>'wrong_sku','cartQty'=>0);
        }
        echo $result = $this->jsonHelper->jsonEncode($res);
} catch (Exception $e) {

    print_r($e->getMessage());die('here');
        if($e->getMessage() == "This product is currently out of stock.")
        {
            $res = array('result'=>'other','cartQty'=>0,'reason'=>$e->getMessage());
        }
        else
        {
            $res = array('result'=>'other','cartQty'=>0,'reason'=>"Invalid  Ajax Request(Network error) or Product is out of stock.");
        }
        echo $result = $this->jsonHelper->jsonEncode($res);

}   
}

}
  • this sometimes happens because of some extra empty lines before the php tag – magefms Mar 25 at 7:50
  • checked the total code and copy the my total code in above question.where i am mistaken.please help me – Ram Sampathi Mar 25 at 7:53
  • I have checked your code and there's nothing wrong that I can see to be the source of your error – magefms Mar 25 at 7:59
  • make sure your editing your file in UTF-8 encoding – magefms Mar 25 at 8:00
  • how can i edit the file in UTF-8 encoding in netbeans? – Ram Sampathi Mar 25 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.