View Full Version : Adding javascript into PHP

05-25-2007, 12:22 AM
How to add javascript into PHP

How would I make this work?


Lets say I have this javascript:

<a href="search.htm" onClick="return overlay(this, 'subcontent2', 'rightbottom')">login</a>

and I want to add it into this PHP:


// Are they a guest?

if ($context['user']['is_guest'])


// Show a login box...

// Uncomment below to show login box

// ssi_login();

// ... and a little notice about registering

echo '

Welcome, <b>Guest</b>, Please **THE JAVASCRIPT HERE** or';

echo '

<a href="', $scripturl, '?action=register">register</a>';


// Otherwise, a user here :)



// Show them a nice welcome notice


echo ' ';

// And a logout link




05-25-2007, 02:55 AM
Don't worry, found a solution:

<a href="#" onclick="return overlay(this, \'subcontent2\', \'rightbottom\')">login</a>

Just add the backslashes.

05-25-2007, 12:23 PM
The problem was in your quotes.
Both javascript and PHP share the same quotes (single quote ' and the double quote ") so when you place a piece of javascript code into PHP - you need to tell PHP to ignore the javascript quotes that interfer - as Master-T did - by using the \ character.
Of course - you could also break it up so that the quotes don't interfer with each other - like this:

$link = "return overlay(this, 'subcontent2', 'rightbottom')";
$link = '<a href="search.htm" onClick="'.$link.'">login</a>';

I prefer the latter because I find it easier to read - even it it is more work.

05-25-2007, 04:09 PM
One of many reasons to break out of PHP parsing mode when outputting HTML.
<?php if($context['user']['is_guest']) { ?>

Welcome, <b>Guest</b>.
Please <a href="search.htm" onclick="return overlay(this, 'subcontent2', 'rightbottom');">login</a>
or <a href="<?php echo $scripturl; ?>?action=register">register</a>.

<?php } else {
} ?>