Home > database >  How to replace a html div with another div using just PHP?
How to replace a html div with another div using just PHP?

Time:11-23

I wanted a div to show after a number of seconds, thus I have made it into two parts, one is a php that echoes that div, and the second is a javascript that replaces the div with another div after some seconds. The problem is before that javascript is executed, The div code shows for 2-3 seconds. Which I do not want. May be we can do this in just PHP? This is the PHP code

if(isset($_GET['id']))
{
$slide = $_GET["id"];
$mytitle='Your id is '.$slide.' ,Welcome';
$murl='"https://example.com/?id='.$slide.'"';
echo '<div id="countdown"> </div>';
echo '<div id="loader"></div>';
echo '<div id="welcome"><a href='.$murl.'>'.$mytitle.'</a></div>';
</div>';
}

This is the javascript

<script>
window.onload = function() {
var countdownElement = document.getElementById("countdown"),
    welcomeButton = document.getElementById("welcome"),
    loader=document.getElementById("loader"),
    seconds = 30,
    second = 0,
    interval;

    welcomeButton.style.display = "none";

interval = setInterval(function() {
    countdownElement.firstChild.data = "Preparing your welcome in "   (seconds - second)   " seconds, Please wait";
    if (second >= seconds) {
        welcomeButton.style.display = "block";
        loader.style.display="none";
        clearInterval(interval);
    }

    second  ;
}, 1000);
}
</script>

CodePudding user response:

You won't be able to so dynamic changes to your page using php.

Here, the issue is that the javascript hides your welcome div. You can add style="display: none" to the div in the php part, so that when the page loads, the div is already hidden.

You can remove welcomeButton.style.display = "none"; frome the javascript as it wont

CodePudding user response:

Disclaimer: I'm 99.99% sure you need to use JS.

However, there is a way to dynamically replace elements after a certain timeout using only PHP. You can achieve this by redirecting the user to another page (or the same but with certain URL query params, like ?welcome=off), see Page redirect after certain time PHP which suggests using header( "refresh:5;url=wherever.php" );

But as I mentioned in the first line, in virtually any normal situation you should prefer to use JS to do this stuff. For example, if you have a form and the user starts typing - they might lose progress when the page redirects.

  • Related