Search code examples
javascriptjquerycodeigniterproject-layout

codeigniter where to put common js php code


I have a site developed in codeigniter.
In many page of my site I have more equal function javascript/jquery with some string in PHP like this:

function change_city_by_nation(nation_id){
        var site_url_city ="<?php echo(site_url('/backend/city/get_city_by_nation_id')); ?>";
        $.ajax({   
            url: site_url_city, 
            async: false,
            type: "POST", 
            data: "nation_id="+nation_id, 
            dataType: "html", 

            success: function(data) {
                $('#city').empty();
                $(data +' option').each(function(index){
                    $('#city').append($(this).html());
                });
                $('#city').prepend("<option value='0' selected='selected'>Tutte le città</option>");
            }
         });
    }

Where is the best place to collect all this javascript function with some string in php? - JS file (but I have to pass the php string when I call it)
- Helper (but how?)
- file php where declare the function JS like common.php(but where to put it and how to call it?)

Have you some solution for my scope? Thanks


Solution

  • If you need to group those scripts, you can make a regular .js file but with modified function parameters - make all the values sent by PHP actually become function parameters. So, for example,

    function change_city_by_nation(nation_id){...}

    becomes

    function change_city_by_nation(url_from_php, nation_id){...} etc...

    And of course, you need to modify the function bodies and function calls (from the views) afterwards.

    However, if you have a function that is used only on a single page, it's perfectly acceptable to leave the JS function there, and embed the PHP values just like you did in your example.