Reputation: 92581
I am wondering about how people go about using CodeIgniter and jQuery for AJAX.
In your AJAX request you have
{
url : ???,
data : {a:1,b:2},
success: ....
}
So, how do you build the URL?
Do you
site_url()
to build the URL<script>var base_url = '<?php echo site_url(); ?>';</script>
. Then in your external js files have url: base_url+'rest/of/path/';
Upvotes: 4
Views: 2702
Reputation: 361
if you are writing your ajax in external file then you can define your base url in the view file like
<script>
var base_url = '<?php echo base_url(); ?>';
</script>
Then on your external ajax file write
url : base_url+'controllerName/functionName',
Upvotes: 2
Reputation: 1293
Usually I make a small javascript in my header, in which I create a base_url and site_url variable (usually being properties of an object I name CI, but that's a personal preeference). I fill these values by echoing the values with PHP. If you make that the first loaded script, you'll always have the site_url available in JS.
Since I'm on mobile I can't post the source now.
Upvotes: 0
Reputation: 81
It can also be done by loading a view that contains your JavaScript.
I currently load JavaScript from a view at the end of the rendered page. Since it is a PHP file with html <script>
in it, you can use the URL helper functions like site_url()
to generate the URLs you need for each function.
An example view might contain:
<script>
$.ajax{
url : "<?=site_url("controller/function")?>",
data : {a:1,b:2},
}
</script>
That will get you CodeIgniter generated URLs for your JavaScript. You could even pass variables into the view for more control over your js.
Upvotes: 0
Reputation: 544
I have my all my js in an external file and load it in my template.
For specific ajax requests, just call the page as you normally would.
$.ajax({
type: 'POST',
url: '/ajax/login',
data: blabla,
success: function(data) {
// do something
},
dataType: 'json');
});
In answer to your question, I've had no need to specify the base url, as putting '/' before the controller name sets the root of the site automatically. You could also use ../ etc
Upvotes: 4