David Coder
David Coder

Reputation: 1138

Call controller by ajax but returning html instead of just json data in magento 1.9

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.

Upvotes: 0

Views: 4168

Answers (3)

Piyush
Piyush

Reputation: 455

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));

Upvotes: 0

roshni
roshni

Reputation: 321

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.

Upvotes: 0

sorak
sorak

Reputation: 2633

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.

Upvotes: 2

Related Questions