Magento 1 – How to Use Ajax to Call a Function in Backend Custom Module

ajaxbackendmodule

i have a controller, a index function like this.

public function indexAction()
{

    $this->loadLayout()
        ->_setActiveMenu('mycustomtab')
        ->_title($this->__('Index Action'));

    $collection = Mage::getModel('trackcode/trackcode')->getCollection();


    foreach ($collection as $code) {
        //echo $code->getOrder_id();
    }
    $this->_addContent($this->getLayout()->createBlock('trackcode/adminhtml_trackcode')->setTemplate('test/abc.phtml'));
    $this->_addContent($this->getLayout()->createBlock('trackcode/adminhtml_trackcode'));

    $this->renderLayout();
}

in a same controller:

public function ajaxAction() {
    echo 'test';

}

A abc.phtml contains a jquery function try to call above controller ajax action.

<script language="javascript">

jQuery(document).ready(function(){
    jQuery('.checkOrder').click(function(){

        jQuery.ajax({url: "adminhtml/trackcode/ajax", success: function(result){
            //$("#div1").html(result);
            alert(result);
        }});
    });
});
</script>

But the alert return a full page of backend magento html code.

Anyone know how to use ajax call a controller function?

Best Answer

Use below code

<script language="javascript">

jQuery(document).ready(function(){
    jQuery('.checkOrder').click(function(){

        jQuery.ajax({url: "<?php echo Mage::helper("adminhtml")->getUrl("adminhtml/trackcode/ajax"); ?>", success: function(result){
            //$("#div1").html(result);
            alert(result);
        }});
    });
});
</script>
Related Topic