Magento – Magento 1.9.3.3 – How to return a JSON array from a controller to ajax

ajaxjsonmagento-1.9.3.3

I have a ajax call to a controller (suburbSearchAction) which retrieves a list of suburbs based suburb text received from the user

Ajax call

inputSuburbData = jQuery(inputSuburb).val().trim();

        jQuery.ajax({
            type: 'POST',
            url: '/service/Index/suburbsearch',
            data: {inputSuburbData:inputSuburbData},
            complete: function(responseData) {

                console.log(responseData);

            },
            error:function(response){

                console.log('Response Error');
                console.dir(response);
            }
        });

Controller Code

<?php

class Vendor_Service_IndexController extends Mage_Core_Controller_Front_Action
{
    public function suburbSearchAction()
    {

        /* Get Suburb text from POST Request */
        $suburbNameQuery = $this->getRequest()->getParam('inputSuburbData');

        /* Retrieve Service Model at: Vendor/Service/Model/Shipping/Carrier/Ram.php */
        $model = Mage::getModel('vendor/shipping_carrier_ram');
        Mage::register('suburb_query', $suburbNameQuery);
        $model->_getSuburbs();
        $suburbResultArray = Mage::registry('suburb_resultset');

        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($suburbResultArray));
    }
}

I can confirm the following:

  • The ajax call calls the controller suburbSearchAction()

  • The varibale in the controller $suburbResultArray has an array of suburbs. so everything is working up till here

My problem is i am unable get the response json to return back to the JavaScript file on completion of the ajax call. it simply returns nothing. The responseData object has no Json array in it.

So basically i want to return json from my controller to my javascript file.

Am i missing anything?

Thanks

Best Answer

use this one.

public function suburbSearchAction()
    {

        /* Get Suburb text from POST Request */
        $suburbNameQuery = $this->getRequest()->getParam('inputSuburbData');

        /* Retrieve RAM Model at: Webtonic/Ram/Model/Shipping/Carrier/Ram.php */
        $model = Mage::getModel('ram/shipping_carrier_ram');
        Mage::register('suburb_query', $suburbNameQuery);
        $model->_getSuburbs();
        $suburbResultArray = Mage::registry('suburb_resultset');

        //$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($suburbResultArray));
$this->getResponse()->clearHeaders()->setHeader('Content-type','application/json',true);
        $this->getResponse()->setBody(json_encode($suburbResultArray));
    }
}

More Information Ref :: https://raivis.com/returning-json-response-from-magento-controller-action/