MKJ
MKJ

Reputation: 133

How to auto display button if condition in PHP is true?

I want to auto display (without refreshing the page) button if, IF condition in PHP is true.

I tried:

<?php if($diffex >= "90"){  ?>
      <button class="btn btn-large btn-primary" type="submit" style="float:right;" name="btn-resend">
         Resend OTP
      </button>
<?php }  ?>

But the above code needs the page to be refreshed and I want it without refreshing it.

My $diffex is calculated as under:

<?php
$eotd="";
$otd="";
if(isset($_GET['od'])){
    $eotd = $_GET['od'];
    $otd = base64_decode($eotd);
}
date_default_timezone_set('Asia/Calcutta');
$cdate = date('Y-m-d H:i:s ', time());
$scdate = strtotime($cdate);
$dscdate = base64_encode($cdate);
$deotd = strtotime($otd);
$diffex = $scdate - $deotd;
?>

Actually, I need this for displaying Resend Option if the current time is greater than the time in URL by 90s

Upvotes: 0

Views: 1767

Answers (2)

Phillip Elm
Phillip Elm

Reputation: 2194

As you've already noted, there is no way to do this in server-side in PHP. You'll need JavaScript running on the client side to update the DOM whenever the button should be displayed or hidden.

At the simplest level, to do what you're asking, you'll probably end up sending AJAX requests to a PHP script that will respond to your client-side JavaScript in JSON. Once you have that data, you can update the view from there.

Example:

check_diffex.php

<?php

header('Content-Type: application/json');

// You would calculate a real value here

echo json_encode([
  'diffex' => 101
]);

JavaScript

var checkState = function(){
  jQuery.ajax({
    url: '/check_diffex.php'
  }).done(function(data){
    var button = jQuery("#myButton");
    if(data.diffex >= 90) {
      button.show();
    } else {
      button.hide();
    }
  });

}

checkState();
setInterval(checkState, 10);

The tricky part with something like native JavaScript and jQuery is deciding how to structure your code that checks that diffex >= 90 with the rest of your application. A lot of quick and dirty implementations will quickly turn into a headache, even for the simplest of "if this, then that" checks.


These days, the most accessible and maintainable way to do what you're asking is to adopt a Single Page Application (SPA) framework, such as:

I highly recommend you take a look at Vue, as you can integrate it into existing projects without having to rewrite the entire front-end.

Upvotes: 2

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

php script can be executed on server only so without refresh, you can not get php code executed. So when you get the page first time, $diffex will have some value and based on it, you can either get the button on page or not.

Now, until you refresh the page, $diffex variable will not get updated with new value (if changed).

So you should either workout using javascript or jQuery.

Upvotes: 0

Related Questions