Gendarme Gendarme - 7 months ago 14
HTML Question

JavaScript in PHP-echo is not noticeable

In my HTML-page I have a

form
with
action="register.php"
and a
<p id="slogan">
. I want the PHP-code in
register.php
to change the value of the
<p>
by echoing some Javascript.

However, the paragraph is not changing in my HTML-page and I do not understand why.

This is what my simplified HTML-page contains:

<body>
<p id="slogan"> hello </p>

<form action="../scripts/register.php" method="post">
...
</form>
</body>


This is what my simplified register.php contains:

<?php
...
if (mysqli_query($conn, $sql)) {
header("Location: http://www.google.com");
echo "<script>
document.getElementById('slogan').innerHTML = 'Character successfully introduced.';
</script>";
sleep(3);
}
?>


The echoed JavaScript is supposed to change
"hello"
to
"Character successfully created."
.

The reason behind
sleep(3)
is to wait three seconds so that you have time to notice the updated paragraph before getting redirected to Google.

Answer

The problem is that since PHP is back-end and JavaScript is front-end, the whole PHP-script has to finish before any JavaScript is executed. This means that the sleep(3) happens before the execution of the JavaScript and totally kills its purpose. All it does is to waste three seconds of your time.

If you want to output a message and also redirect, you need to come up with other ways of doing it. However, that is another topic.