srikanta
srikanta

Reputation: 15

Change background color of a button in javascript is not working

I have created a button in a file index.php

.button_round {
  border: none;
  padding: 7px;
  display: block;
  margin: 20px 2px;
  border-radius: 50%;
  background-Color: red;
}
<button class="button_round" id="link_button"> </button>

I want to change the color of the button based on condition as below in linkcheck.php file.

<?php
    include ("config.php");
    include ("index.php");

    //get max timestamp 

    $sql_query = "SELECT MAX(time) AS max_time FROM table_data";
    $execute_query = $conn->query($sql_query);
    $sett_row = $execute_query->fetch_assoc();
    $max_time =  $sett_row["max_time"];

    // today date timestamp
    $date = new DateTime();
    $time =  $date->getTimestamp();
    if((($time*1000) - $max_time) > 20000)
    {
?>
    <script type="text/javascript">
        document.getElementById("link_button").style.backgroundColor = "#FFFFFF"
    </script>
<?php       
    } else {
?>
    <script type="text/javascript" >
    document.getElementById("link_button").style.backgroundColor = "#7FFF00"
    </script>
<?php       
    }
?>

Also linkcheck.php is executing in every second through other javascript file name custom.js

setInterval(function() {
    if(true) {
        $.ajax({
            type: "POST",
            url: "linkcheck.php",
            success: function(data){
            }
        });
    }  
},1000); 

But it is not working. Please can someone provide a solution?

Upvotes: 0

Views: 158

Answers (2)

Pete
Pete

Reputation: 58442

I would change your php file to just echo the colour based on the if:

if((($time*1000) - $max_time) > 20000)
{
  echo "#FFFFFF";
}
else
{
  echo "#7FFF00";
}

Then in your ajax, you can just use the data variable in your response (assuming nothing else is output in the php file):

$.ajax({
  type: "POST",
  url: "linkcheck.php",
  success: function(data) {
      document.getElementById("link_button").style.backgroundColor = data;
  }
});

Please note making a db call every second is not very good

Upvotes: 1

raviramani
raviramani

Reputation: 522

i think you need to write <style> not <script>

if((($time*1000) - $max_time) > 20000)
{
?>
<style>
#link_button{
  background:#FFFFFF;
}
</style>
<?php       
}
else
{
?>
<style>
#link_button{
  background:#7FFF00;
}
</style>
<?php       
}
?>

Upvotes: 1

Related Questions