Daanvn
Daanvn

Reputation: 1266

How to echo javascript code in php

I am having a problem with how to echo javascript in php. I have a form which on submit will execute itself and echo some text and will redirect to a page in 5secs. I am currently echoing this:

header("Refresh: 5;url=index2.php?ID=".$objResult["ID"]."");

echo '<html>';
echo '<head>';
echo '<title>Klant toevoegen</title>';
echo '<link rel="stylesheet" href="style.css" type="text/css" media="screen" />';
echo '</head>';
echo '<body>';
echo '<fieldset>';
echo ''.$Naam.' is added to the database, u will be redirected in a couple of seconds.<br><br>';
echo '</fieldset>';
echo '</body>';
echo '</html>';

The javascript I have is a countdown which counts down from 5 to 1. The code is this:

<script>

var countdownFrom = 5;  // number of seconds
var countdownwin;

var stp;
function CountDownStart() {
 stp = setInterval("CountDownTimer('CountDownTime')",1000)
}

function CountDownTimer(id)
{
if (countdownFrom==0) {clearInterval(stp); window.close(); }
else     {
            var x
            var cntText = "Closing in "+countdownFrom+" seconds";

        if (document.getElementById)
    {
        x = document.getElementById(id);
        x.innerHTML = cntText;        }
    else if (document.all)
    {
        x = document.all[id];
        x.innerHTML = cntText;        }
    }
countdownFrom--
}

</script>
   <title>Untitled</title>
</head>

<body onload="CountDownStart()">

<Div id="CountDownTime"></div>

</body>

Now I would like to echo this countdown script to replace the <fieldset> in the html. I have tried several things like just add the whole code in 1 echo ''; and I tried to echo all the lines seperately but with both it crashes my whole script. If anyone knows how to do this it would be great!

Upvotes: 0

Views: 29465

Answers (3)

Firezilla12
Firezilla12

Reputation: 110

You can put the script in a separate .js file and echo the script tag:

<? echo "<script type='text/javascript' src='path/to/script.js' ></script> ?>

Don't forget to remove any HTML tags from the JS file, like <body>, <head>, etc.

Upvotes: 0

Victor
Victor

Reputation: 1469

Try to use

echo <<<EOT
   /*  some text here */
EOT;

Upvotes: 2

ilyail3
ilyail3

Reputation: 72

I Wouldn't write all those echo's, instead, leave all the HTML and JS outside the PHP block

<?php
some php code
?>

HTML AND JS

<?php
More php if required
?>

And use

<?=$Naam?>

To inject your values where required

Alternatively you should look into template engines

Upvotes: 3

Related Questions