简体   繁体   中英

Real Time DIV background color update based on database value

I want the div to change color based on the value that is retrieved from the database. The current code doesn't give any color and uses the set css color.

Main div css

.status{    background: #000;   }

status.php

if ($user_data['status'] === "1") { echo "online"; } 
else {                              echo "offline";  }

The ajax function

 $(document).ready(function() {
    setInterval(function(){
      $.ajax({
        url: 'status.php',
        type: 'GET',
        success: function(data) {
            if (data === "online") {
               $('.status').css('background', '#40A547');
            } else { 
               $('.status').css('background', '#7f8c8d');
            }
        }
    });
   }, 2000);
});

The main div

 <div class="status">something</div>

Please help me out. All help will be much appreciated!

The problem can be identified use this code :

$(document).ready(function() {
    setInterval(function(){
    $.ajax({
        url:'status.php',
        datatype:"application/json",
        type:'GET',
        success:function(data){
            if (data === "online") {
                $('.status').css('background', '#40A547');
            } else {
                $('.status').css('background', '#7f8c8d');
            }
        },
        error:function(){
            //if pointer is comming it means there is some error in the back end code
        }
    });
    }, 2000);
});

Now check your in the firebug it will show you the error details , if you don't have firebug add it and then check.

also put some content in the div so that it will be visible. If there are no content div doesn't appear.

Hope this will help!

You don't have anything in your div, so it's basically 0 height and width so you don't see anything (which is what I assume you mean by "current code doesn't give any color").

If you specify a height and width, or add something inside your div (even a &nbsp; , you should see the background color.

That means you are not getting 'online' back from your ajax. you need to edit your PHP code that you are AJAXing to purely say 'online', no divs or markup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM