best practice to use action url while calling ajax in cakePHP

11,036

Solution 1

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'});

Solution 2

I'm updating Paul Dragoonis's answer to reflect the latest CakePHP version (2.2).

In your layout file, set the JavaScript variable with CakePHP's JSHelper: <?php echo $this->Js->set('url', $this->request->base); ?>, where $this->request is an instance of CakeRequest and gives information on the current request.

After the line above, write the buffer with <?php echo $this->Js->writeBuffer(); ?>.

Then, you can access this variable in JavaScript with app.url.

Solution 3

@irtiza your answer is appreciated but for cakephp latest version 3.x this will work otherwise you will get routing error.

ulr:'<?php echo \Cake\Routing\Router::url(array('controller' => 
'controllername', 'action' => 'actionname')); ?>'

Solution 4

in reply to Paul Dragoonis you can use $this->webroot if you use subfolders.

Solution 5

use

echo Router::url(array('controller' => 'Users', 'action' => 'all'));

Will output;

/Users/all

in js

$.post({url : "<?php echo Router::url(array('controller' => 'Users', 'action' => 'all')); ?>"})
Share:
11,036
RSK
Author by

RSK

Rubyist / JavaScripter Ex Yeoman Backbone generator maintainer Open source enthusiast Blogger @ PHPRepo and personal blog Coder @ Codemancers Find my presence on web

Updated on June 20, 2022

Comments

  • RSK
    RSK almost 2 years

    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