Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to combine javascript with php

Hi,

My javascript is,

var fvisit  = setTimeout(function(){
        $.niftyNoty({
            type: 'dark',
            title: 'Hello',
            message: 'Lorem ipsum dolor sit amet consectetuer <br> adipiscing elit sed diam nonummy nibh.',
            container: 'floating',
            timer: 55000
        });
        clearTimeout(fvisit);
     }, 3000);

PHP script,

<?php echo validation::safeOutputToScreen($Auth->getAccountScreenName()); ?>

I try combine script like below,

var fvisit  = setTimeout(function(){
        $.niftyNoty({
            type: 'dark',
            title: 'Hello <?php echo validation::safeOutputToScreen($Auth->getAccountScreenName()); ?>',
            message: 'Lorem ipsum dolor sit amet consectetuer <br> adipiscing elit sed diam nonummy nibh.',
            container: 'floating',
            timer: 55000
        });
        clearTimeout(fvisit);
     }, 3000);

But get output like,

Hello getAccountScreenName()); ?>

Thanks

David Bath
David Bath
25,940 Points

Is this script inside a php page?

David Bath
David Bath
25,940 Points

Is this script inside a php page?

Hi David Bath,

The script inside javascript.

Thanks

1 Answer

andi mitre
STAFF
andi mitre
Treehouse Guest Teacher

You cannot run PHP inside javascript. You can get away with certain things such as having html that invokes javascript functions in PHP variables etc..

David Bath
David Bath
25,940 Points

Exactly. The PHP parser isn't going to parse the Javascript in a separate file. However, if that script was inside a script tag in a PHP page, then it should get parsed before rendering and should behave as you intend.

Fixed! I put the script in php

<script type="text/javascript"> var fvisit = setTimeout(function(){ $.niftyNoty({ type: 'dark', title: 'Hello <?php echo validation::safeOutputToScreen($Auth->getAccountScreenName()); ?>', message: 'Lorem ipsum dolor sit amet consectetuer <br> adipiscing elit sed diam nonummy nibh.', container: 'floating', timer: 55000 }); clearTimeout(fvisit); }, 3000); </script>

Thanks you so much