Question

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

Was it helpful?

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.

OTHER TIPS

It's somewhat common practice to create a JS variable in your <head> (or somewhere before your main JS file) that refers to a base URL, or other common variables needed by JS that are generated by the back end.

<script>
var SITE_URL = "<?php echo site_url(); ?>";
</script>

Then, your Javascript file would be included at the end of your <body> HTML source, and it can utilize these variables where necessary.

How you generate the initial variables will depend on how you handle templates in your application. A common header / footer will make the whole process easier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top