Friday, January 21, 2022

[FIXED] CodeIgniter base_url

Issue

I have a problem with codeigniter base_url. My base_url is $config['base_url'] = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME'])... (http://test.localhost/)... but when I do an ajax request for example I use <?= base_url(); ?>installer/test and the response is "No direct script access allowed".

I try adding to base_url index.php (http://test.localhost/index.php/) and this problem is solved but now when I load an css using base_url like this: <?= base_url(); ?>assets/css/installer.css the css is not loading but if I remove index.php the css load correctly but the ajax request response "No direct script access allowed".

Obviously I think that I have a problem with my configuration but I don't find the error. I need that the ajax request and css load under the same base_url because the code is big and I can't change all instance of base_url.


Solution

base_url and site_url should be like this:

base_url() = http://test.localhost/
site_url() = http://test.localhost/index.php/

If you need to load URL resources like CSS, JS, images etc., use base_url(), otherwise site_url() is better. That means in your ajax request you can set the url like this:

var serviceUrl = "<?php echo site_url(); ?>your_controller/your_method";
            var returnResult = $.ajax({
                                            url: serviceUrl,
                                            data: {'id': id, .....},
                                            type: 'post',
                                            dataType: 'json'
                                        });

Or you can set the url like this:

var serviceUrl = "<?php echo base_url(); ?>index.php/your_controller/your_method";
            var returnResult = $.ajax({
                                            url: serviceUrl,
                                            data: {'id': id, .....},
                                            type: 'post',
                                            dataType: 'json'
                                        });


Answered By - Abdul Salam

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.