Reputation: 4811
Just getting into Codeigniter and I'm planning out a large application. I'm a bit confused about how CI handles JS files and AJAX requests.
I am using mod_rewrite with my project.
In a regular webpage, I'd reference separate JS scripts at the header of my doc to keep my code segregated and clean. Since I'm using mod_rewrite, I need functions from the url helper to find my files. This is a problem in separate js docs because they don't execute php. So when it comes to AJAX calls, how am I supposed to reference a PHP controller function from my JS file when I don't have use of the site_url() function?
How would I go about writing functions that can be accessed through AJAX but not through the address bar? So, let's say I have a User Controller. You can go to user/pictures and you can see their pictures. You go to user/friends and you can see their friends. But I don't want you to be able to go to User/getData and see all the printed out raw data.
tl;dr What is standard JS and AJAX practice when using separate docs and mod_rewrite?
Cheers guys.
Upvotes: 0
Views: 75
Reputation: 6016
I also declare a js variable in the <head>
like
var baseUrl = '<?php print(base_url()); ?>';
Then when you do your AJAX call you can call the controller like
baseUrl + 'controller/method'
In terms of making sure that methods can only be called from AJAX calls and not through the address bar one option is to send a post value and check for this before you do anything like
if($this->input->post('ajax_call'))
{
//Do something
}
If you put all your ajax methods into the same controller you'd only have to have this check once in the __construct()
Upvotes: 1
Reputation: 7475
What I personally do is declare a js variable in the header section of my template before any js declaration like this:
var base_url = <?=base_url()?>
This base_url
will then be accessible by any js file you integrate. About the second point you can always redirect the user from your controller like this:
public function some_function(){
if($this->input->post(null)){
//your ajax code here
}else{
redirect(base_url(), 'refresh')
}
}
Upvotes: 1