Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how not to hard-code codeigniter link in js file

i wrote the routine below to retrieve city based on selected country for my codeigniter application.

$(document).ready(function() {
    $("select#cbo_country").change(function() {
        $.post("http://localhost/main/index.php/city/get_data_by_country", {
            int_country_id  : $(this).val()
        },
        function(data) {
            // some code here
        },'json');
    })
});

as you can see, i hard-coded the url (http://localhost/main/index.php/city/get_data_by_country) and i know it's a bad practice but i can't help it.

is there a nice clean way to not hard-code the url? i used to use codeigniter's base_url(), but since i move the routine to a js file, i am no longer able to use the function.

like image 691
dqiu Avatar asked Feb 12 '26 08:02

dqiu


1 Answers

Taken (mostly) from my answer on How to get relative path in Javascript?.

You've got two options:

  1. Build a configuration/ preferences object in JavaScript which contains all your environment specific settings:

     var config = {
         base: "<?php echo base_url(); ?>",
         someOtherPref: 4
     };
    

    and then prefix the AJAX url with config.base.

    You have to place the config object in a place which is parsed by PHP; the standard choice is inside the <head> HTML element. Don't worry its a small config object, whose contents can change on each page, so it's perfectly warrented to stick it in there.

  2. Use the <base /> HTML tag to set the URL prefix for all relative URL's. This affects all relative URL's: image's, links etc.

Personally, I'd go for option 1. You'll most likely find that config object coming in handy elsewhere.

like image 51
Matt Avatar answered Feb 14 '26 22:02

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!