Magento 1.9 – How to Get Output in Phtml File from Controller Response

controllersmagento-1.9phtml

In controller file I put this,

$result = "success";
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));

How to fetch output in phtml file?

Best Answer

Here i am showing you sample example using ajax request with json responsce

Template file: /app/design/frontend/rwd/default/template/pay/index.phtml

<div id="results" style="width:100px; height: 200px;border:1px solid red;">
</div>

<button type="button" id="id1" class="myButton">Click Me 1!</button>
<button type="button" id="id2" class="myButton">Click Me 2!</button>

<script>
    jQuery(document).ready(function() {
          jQuery(".myButton").click(function() {
            var id = this.id;
            jQuery.ajax({      
            type: "POST",
            data: 'pid=' + id,
            dataType: 'JSON',
            url: "<?php echo Mage::getBaseUrl().'pay/index/sampledata' ?>",
            success:function(response){                       
                if (response){

                 jQuery('#results').html(response.pid);

                }
            }

            });
        });
     });
</script>

IndexController.php /app/code/local/Excellence/Pay/controllers/IndexController.php

 public function sampledataAction() 
 {
     $post = $this->getRequest()->getPost();
     $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($post));

 }

Note: Please try this code in default magento and custom module. thanks