Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 319
RSK Avatar asked Jul 28 '10 11:07

RSK


People also ask

What does URL do in AJAX?

ajax() Function. The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .

What is data AJAX URL?

ajax(url,[options]); Parameter description: url: A string URL to which you want to submit or retrieve the data. options: Configuration options for Ajax request. An options parameter can be specified using JSON format.


2 Answers

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'});
like image 184
Paul Dragoonis Avatar answered Oct 17 '22 04:10

Paul Dragoonis


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.

like image 27
linkyndy Avatar answered Oct 17 '22 06:10

linkyndy