Magento – Get custom controller url in ajax in magento 1.9

ajaxcontrollersmagento-1.9

I am trying to get the custom controller in ajax my controller file is located in
app/code/local/Minicart/Quick/controllers/minicartcontrolle‌​r.php

and the action name of the controller is add_to_minicart here is my code that i tried to access

  function addtoCart(){
    jQuery("#success_message").show();
    jQuery("#success_message").html('<img src="/demo/media/images/loading-round.gif" alt="Loading..." width="77" height="73">');
    var url;
    url = jQuery('#product_addtocart_form').attr('action');

    url = url.replace("checkout/cart", "ajax/index"); // New Code
    if ('https:' == document.location.protocol) {
        url = url.replace('http:', 'https:');
    }
    var data = jQuery('#product_addtocart_form').serialize();
        data += '&isAjax=1';
    try {
        jQuery.ajax({
            url:url,
            dataType:'json',
            type:'post',
            data:data,
            success:function (data) {
                if(data.status=="SUCCESS"){
            //jQuery("#success_message").html(data.message);
            jQuery("#success_message").html(data.message);
             minicartAjax();
             var qty = jQuery("#qty").val();
             var curqty = jQuery(".header-minicart .count").html();
             var newqty=parseInt(qty)+parseInt(curqty);
             jQuery(".header-minicart .count").html(newqty);
                }
            }

        });
    } catch (e) {

    } 


}
function minicartAjax(){
    var url = "<?php echo Mage::getUrl('quick/controllers/add_to_minicart');?>";
    alert(url);
    jQuery.ajax({
        url: url,
        dataType: 'json',
        success: function(data){
            //Your minicart html
            alert("hii");
        }
    });
}

when i alert the url it just display this <?php Mage::getUrl('quick/controllers/add_to_minicart');?> how can i get the url of my custom controller

Best Answer

you forgot an echo before Mage::getUrl.

var url = "<?php echo Mage::getUrl('quick/controllers/add_to_minicart');?>"; 

If you are doing this in a javascript file it won't work. Js files don't interpret <?php ?> tags.

What you can do instead is to change your function to look like this

function minicartAjax(url){
    jQuery.ajax({
        url: url,
        dataType: 'json',
        success: function(data){
            //Your minicart html
            alert("hii");
        }
    });
}

and in the template that calls this javascript, call it like this

minicartAjax('<?php Mage::getUrl('quick/controllers/add_to_minicart');?>')
Related Topic