RSK RSK - 3 months ago 16x
Ajax Question

best practice to use action url while calling ajax in cakePHP

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 : "/"})

in cakePHP we
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


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.

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

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

$.post({url: myBaseUrl + 'controller/action'});