views:

90

answers:

2

hello friends,
I am using ajax with jQuery in my cakePHP application.
and my javascript function is placed inside a javascript file.

now in my local system the files are kept in "/sample" directory so the the path while i call the function will be

in ajax.js

$.post({url : "/sample/controller/action"})

but after hosting it the url will become

$.post({url : "/mydomain.com/controller/action"})

in cakePHP we $html->url to generate urls
but since this code is in js file i can't use that function

i don't want to change the all ajax action urls manually before hosting

+4  A: 

What to do is in your master template for your cake app create a global javascript variable that can be used throughout your application. Make sure it exists befor you do any JS includes too.

<head>
    ...
    <script type="text/javascript">var myBaseUrl = '<?php echo $html->url; ?>';</script>
    ...
    <script type="text/javascript" src="mycustomJSfile.js">
    ...
</head>

Now you can do things like this from any view file you have in your MVC framework app.

$.post({url: myBaseUrl + 'controller/action'});
Paul Dragoonis
I do this for every web application i write using any framework. It's even more handy if you're using Smarty and need the baseUrl in javascript. You'd have to do {/literal}{$baseUrl}{/literal} which is a royal PITA. The above solution solves this nicely.
Paul Dragoonis
A: 

I do it like this. It works across deployments using inbuilt CakePhp functionality:

<?php $Url = Router::url(array('controller'=>'users','action'=>'ajaxUpdateAccess'),true); ?>
<script type="text/javascript">
    function _updateAccess(thisCheck)
    {
        var xmlHttp = createXmlHttpRequestObject();
        var actionURL = '<?php echo $Url ?>';
        ...
Leo