Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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;
         }
    });
});
share|improve this question

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer
    
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. – David Dec 16 '13 at 9:04
    
You're welcome. What do you mean by "double urls"? – ToniTornado Dec 16 '13 at 9:06
    
You need to declare the functions before loading the view and use the variable instead of hey I want this function right now ! :) – David Dec 16 '13 at 9:08
1  
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. – ToniTornado Dec 16 '13 at 9:14
1  
What about defining a var "base_path" and then use it like MyConfig.base_path + "/sub/dir"? – ToniTornado Dec 16 '13 at 9:31

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.

share|improve this answer
    
Thanks for the answer . Maybe the best way is just to include in a php document in script tags. – David Dec 16 '13 at 8:56
1  
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. – Frogmouth Dec 16 '13 at 9:02
2  
You can simply call json_encode() on $links instead of this foreach loop. – ToniTornado Dec 16 '13 at 9:03
    
@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 – Frogmouth Dec 16 '13 at 9:06
1  
Thanks ;) But the basic idea is the same in our answers! – ToniTornado Dec 16 '13 at 9:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.