skip to Main Content

I have created ajax function to call controller, and in conmtroller i have fetched some data and return as json, but in ajax function in response it is printing whole html page, instead of just json data.

Controller:

<?php

class Mage_Catalog_ProductwidgetController extends Mage_Core_Controller_Front_Action
{

    public function execute()
    {
        //$catid = $this->getCategory()->getId();
        $_category = Mage::registry('current_category');
        $catid = $_category->getId();
        $_productCollection = Mage::getModel('catalog/category')->load($catid)
            ->getProductCollection()
            ->addAttributeToSelect('*')
            ->addFieldToFilter('status', 1)
            ->addAttributeToFilter('visibility', 4)
            ->joinField('is_in_stock',
                'cataloginventory/stock_item',
                'is_in_stock',
                'product_id=entity_id',
                'is_in_stock=1',
                '{{table}}.stock_id=1',
                'left');
        foreach ($_productCollection as $_product) {
            $_product->getData();
            $json_products[] = array(
                'name' => $_product->getName(),
                'url' => $_product->getProductUrl(),
                'entity_id' => $_product->getEntityId());
        }

        $this->getResponse()->clearHeaders()->setHeader('Content-type', 'application/json', true);
        $this->getResponse()->setBody(json_encode($json_products));
    }
}

Ajax:

jQuery.ajax({
            type: 'POST',
            url: "<?php echo $this->getUrl('/controller/'); ?>",

            success : function(data){
               console.log(data);
            }
        });

Where I am wrong, it returns page html instead of json data.

3

Answers


  1. Just print the JSON you want returned and die(). That call is only generating raw output, so there’s no reason to run it through a view.

    Login or Signup to reply.
  2. Instead of

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

    Use $this->getResponse()->setBody(Zend_Json::encode($json_products)); to return json output.

    Login or Signup to reply.
  3. First you have to add dataType : 'json' in you ajax param, your ajax code will be

    jQuery.ajax({
                type: 'POST',
                url: "<?php echo $this->getUrl('/controller/'); ?>",
                dataType : 'json',
                success : function(data){
                   console.log(data);
                }
            });
    

    Then in your controller set your response as below

    $this->getResponse()->setHeader('Content-type', 'application/json');
    $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($json_products));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search