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
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.Instead of
Use
$this->getResponse()->setBody(Zend_Json::encode($json_products));
to return json output.First you have to add
dataType : 'json'
in you ajax param, your ajax code will beThen in your controller set your response as below