Best practice using action url when calling ajax in cakePHP

I am using ajax with jQuery in my cakePHP application.
and my javascript function is placed inside the javascript file.

now on my local system the files are stored in the "/ sample" directory, so the path when I call the function will be

in ajax.js

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

but after posting it, the url will become

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

in cakePHP we $html->urlto generate urls
but since this code is in the js file, I cannot use this function

I do not want to change all the actions associated with ajax actions manually before hosting

+5
source share
5 answers

cake, javascript global, . , , JS.

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

, MVC.

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

Paul Dragoonis, CakePHP (2.2).

JavaScript CakePHP JSHelper: <?php echo $this->Js->set('url', $this->request->base); ?>, $this->request CakeRequest .

<?php echo $this->Js->writeBuffer(); ?>.

JavaScript app.url.

+6

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

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

in response to Paul Dragoonis you can use $this->webrootif you use subfolders.

+1
source

use

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

It will be displayed;

/Users/all

in js

$.post({url : "<?php echo Router::url(array('controller' => 'Users', 'action' => 'all')); ?>"})
+1
source

All Articles