dqiu
dqiu

Reputation: 337

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.

Upvotes: 3

Views: 6238

Answers (3)

gen_Eric
gen_Eric

Reputation: 227270

One thing you can do is add a data-baseurl attribute to an element on the page (the body element works). Then you can grab that from the JavaScript file.

<body data-baseurl="<?=base_url()?>">

Then in JavaScript:

$("select#cbo_country").change(function() {
    var baseURL = $('body').data('baseurl')
    $.post(baseURL+"city/get_data_by_country", {
        int_country_id  : $(this).val()
    },
    function(data) {
        // some code here
    },'json');
})

Upvotes: 0

Brandon
Brandon

Reputation: 2125

Change "http://localhost/main/index.php/city/get_data_by_country" to "/main/index.php/city/get_data_by_country" and it will work no matter what your base url is.

This works because the / before main/index.php says "start at the root and go the the index.php file in the main folder".

This is unless your document root folder is set to the main folder, if so, take out the main

Upvotes: 2

Matt
Matt

Reputation: 75317

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.

Upvotes: 10

Related Questions