0

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.

David Coder
  • 1,138
  • 2
  • 14
  • 48

3 Answers3

2

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.

sorak
  • 2,607
  • 2
  • 16
  • 24
0

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.

Syed Waqas Bukhary
  • 5,130
  • 5
  • 47
  • 59
roshni
  • 321
  • 2
  • 5
0

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));
Piyush
  • 457
  • 7
  • 18