0

How can I input results of a PHP array inside a JS-file?

I have this PHP-snippet which returns an Array:

$activiteiten = Project::getProjectnames($_DB);
if(!empty($activiteiten)) {
    foreach($activiteiten as $k => $v) {
        $projectNames[] = $v['project'];
    }
}

How can I get these values inside this JS:

<script>
    $(function() {
        var availableTags = [
            "Option 1",
            "Option 2",
            "Option 3",
            "Option 4"
        ];
        $( "#tags" ).autocomplete({
            source: availableTags
        });
    });
</script>

I want the PHP array in stead of the Option 1, Option 2, Option 3,... But how do I do this?

I'm generating the JS by using a PHP echo-call.

2
  • Are you requesting the page from JavaScript (Ajax), or are you generating the JavaScript with PHP? Commented Dec 18, 2011 at 20:39
  • I'm generating the JS with PHP Commented Dec 18, 2011 at 20:40

3 Answers 3

7
var availableTags = <?php echo json_encode($projectNames); ?>;
Sign up to request clarification or add additional context in comments.

1 Comment

Thats nice and clean, I only suggested a way closest to the orginal code.
1
<script>
    $(function() {
        var availableTags = [
            <?php 
                foreach($activiteiten as $k => $v){
                       echo '"'.$v['project'].'",';
                }
             ?>
        ];
        $( "#tags" ).autocomplete({
            source: availableTags
        });
    });
</script>

4 Comments

That's nice. But how can I use it when generating the JS with PHP?
There are several ways, and these are not the most beautiful ones, but you could have your php logic, then close php tags and put this the above code in: eg: <?php //code here ?> JS here <?php // activiteiten loop here ?> some more JS <?php //end of PHP logic ?>.
Ok, thanks! But I think I'll do it like Ignacio said. It's more compressed :-)
Yeah I agree, as I said, I just wanted to stay close to your code :)
0

What you want to do is json encode that array and echo it in the context of javascript; thus setting a variable equal to it. For example:

<script type="text/javascript">
 var availableTags = <?php echo(json_encode($myArray)); ?>
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.