3

I have now all my javascript code in my views (PHP). But I want to seperate that (for deleting duplicate code). I am currently using CodeIgniter framework and currently I use functions like this :

$(function() {
    $("#serialNumber").autocomplete({
         source: "<?php echo site_url('manage/getSerials'); ?>",
         change: function(event, ui) {
             if (!ui.item) {
                 $(event.target).val("");
             }
         },
         focus: function(event, ui) {
             return false;
         }
    });
});

However you can't use javascript variables inside php.

So should I create for each link a variable and use it like that in my javascript or use the javascript in a seperate php file or is there a better way around it ?

The answer with help from ToniTornado :

First make a function like this :

function getURL(link) {
    var site = "<?php echo site_url(); ?>";
    site += "/" + link;
    return site;
}

Include that in your collection where all your jquery, css files are Then use the function like this (jQuery) :

$(function() {
    $("#serialNumber").autocomplete({
         source: getURL('controller/function'),
         change: function(event, ui) {
             if (!ui.item) {
                 $(event.target).val("");
             }
         },
         focus: function(event, ui) {
             return false;
         }
    });
});
0

2 Answers 2

4

In my opinion, the best way to pass many variables from PHP to Javascript is to collect them in a PHP object, convert the object to JSON and print it out in a script tag on your website.

In your controller:

$config = new stdClass();
$config->site_url = site_url('manage/getSerials');
$config->user_name = 'David';

...pass the $config var somehow to your view.

In your view:

<script type="text/javascript">
  var MyConfig = <?= json_encode($config); ?> // global var "MyConfig"
</script>

It will generate this code:

<script type="text/javascript">
  var MyConfig = {
    site_url: "what/your/function/returned",
    user_name: "David"
  }
</script>

And finally access your vars like this in your Javascript files:

console.log(MyConfig.site_url)

The global Javascript var MyConfig has the additional benefit of having all your dynamic variables namespaced in a Javascript object.

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for answering. I think this is one of the best ways to pass the functions. The problem is that you need to make like double URL's to the same function.
You're welcome. What do you mean by "double urls"?
You need to declare the functions before loading the view and use the variable instead of hey I want this function right now ! :)
Ah ok now i got it. :) To call a PHP function from Javascript "directly" you need an AJAX-request every time you want to call the function - I'm not sure if you would want to do that.
What about defining a var "base_path" and then use it like MyConfig.base_path + "/sub/dir"?
|
1

You can create a php array and add a new item every time you create a link for your js function like:

$links['refence'] = site_url('manage/getSerials');

*refence = name of js variables or name of property of js object that contain all your link.

now at the and of your all view (before ) you may create this:

<script type="text/javascript">
    var refLink = {
        <?php foreach($links as $key => $link): ?>
            <?php echo $key; ?> : <?php echo $link; ?>,
        <?php endif; ?>
    }
</script>

(if you use this prop ondom ready) the obj refLink are evalued like:

var refLink = {
     link1 : "yourpath/action",
     link2 : "yourpath/action2",
     link3 : "yourpath/action3",
}

and now you not need to use php inside complex JS but all inside a single js.

$(function() {
            $("#serialNumber").autocomplete({
                source: refLink.link3,  //link3 is the key of you php array. 
                change: function(event, ui) {
                    if (!ui.item) {
                        $(event.target).val("");
                    }
                },
                focus: function(event, ui) {
                    return false;
                }
            });
        });

It's a way... maybe not the best... but... if you want try.

8 Comments

Thanks for the answer . Maybe the best way is just to include in a php document in script tags.
you can create a view that responds to a url like "base path / config.js" that return a text/javascript header that contain the javascript object or a JSONP... but all depends of your PHP app architecture. I think... the best way is the one that is easiest for you but thought.
You can simply call json_encode() on $links instead of this foreach loop.
@ToniTornado YES. That's true but I don't know what is the best way to do this in terms of server work. If you know... you are welcome. :D
Thanks ;) But the basic idea is the same in our answers!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.