I am currently using ajax in multiple controllers in my application. I implemented the ajax functionality using the jQuery supported version.
$.ajax({
url:'getCountries',
type: "POST",
dataType: "html",
data:"data=" + result,
success: function(data){
//magic...
}
}
});
As you can see from the code above the url of this request is 'getCountries'. This means that if the request is made from
http://localhost/appname/controllername/methodname
the request url will be
http://localhost/appname/controllername/getCountries
However if the url you are using this script is different than in example above, say
http://localhost/appname/controllername/methodname/7
(like in the edit view), then the request url in the ajax call from those urls will change to
http://localhost/appname/controllername/methodname/getCountries
How can I make it so that the request url will be generated automaticly depending on the controller I am currently in?
Please note that the appname in the url path is the name of the root folder of the application and it should be also included so that if the files will be transported to a different server/location the javascript link will stay consistent with the root folder also.
I think you should use full path in your Ajax call and if you use this code in multiple views you could pass ControllerName in some variable:
$.ajax({
url: http://localhost/appname/<?php echo $controllerName; ?>/getCountries
// code
});
In this case you need to use View or Element files (with *.ctp extension) to echo variable to JavaScript code. Alternatively you can echo it to some JavaScript variable in the view and pass it to you external *.js script file.
It works for me in similar cases.
Try this one
$.ajax({
url:"<?php echo $this->webroot . $this->params["controller"]; ?>/yourAction"
});
$this->webroot
contain path to your webroot for example if your app folder located in htdocs/test and you mast access it using localhost/test/
$this->webroot
will contain following string '/test/'
use
echo Router::url(array('controller' => 'controllername', 'action' => 'methodname',7));
Will output;
/controllername/methodname/7
in js
$.post({url : "<?php echo Router::url(array('controller' => 'controllername', 'action' => 'methodname',7)); ?>"})