Magento – Setting AJAX URL for custom module

ajaxjavascriptmoduleurl

I have a JavaScript file in /js/mds/mds_collivery.js. In it I have an AJAX call that should go to magento_install_url/collivery/ajax/cptypes. It will only be used in /checkout/onepage/.

However, if I set the URL to be:

url : "/collivery/ajax/cptypes",

it tries to access

http://localhost/collivery/ajax/cptypes

and if I set the URL to:

url : "collivery/ajax/cptypes",

it tries to access

http://localhost/magento/index.php/checkout/onepage/collivery/ajax/cptypes

I currently hard coded it to

http://localhost/magento/index.php/collivery/ajax/cptypes

but this isn't ideal as the setup procedure for my module would require users to edit this file before it can work.

Is there a JS variable or another way to get the Magento Install Location inside JavaScript?

Best Answer

in app/design/frontend/{interface}/{theme}/template/checkout/onepage.phtml add this code somewhere at the top of the template:

<script type="text/javascript">
var baseUrl = '<?php echo Mage::getUrl('');?>';
</script>

now you should be able to use in your js file this:

url : baseUrl + "/collivery/ajax/cptypes",

Actually you can add the script anywhere in the template (header, footer, ...) just make sure it's in the page you need. Since the checkout page is the only one you need, I suggested adding it in the onepage template.

Related Topic