0

I'm using the JavaScript function setInterval every 30 seconds to check the MySQL table with AJAX. Using AJAX it updates the page with new results without reloading the page.

I would like to use the effect highlight to colour certain records, in the example below this highlights ID 1 and 10:

$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);

I would like to highlight all new records that have been added since the last load.

index.php

// Run polling function every 60 seconds
var myVar = setInterval(myfunction, 30000);

// Load data from check_status page
function myfunction() {
    $.ajax({
        url: "check_status.php", success: function(result2) {
            $("#div2").html(result2);
            $("#title").html("Food Items AUTO Poll");
            $("#image_li_1").effect("highlight", {}, 25000);
            $("#image_li_10").effect("highlight", {}, 25000);
        }
    });
}

check_status.php

// Include and create instance of db class
require_once 'DB.class.php';
$db = new DB();

<?php
    // Fetch all items from database
    $data = $db->getRows();
    if (!empty($data)) {
        foreach ($data as $row) {
?>
            <li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
                <a href="javascript:void(0);" style="float:none;" class="image_link">
                    <?php echo $row['name']; ?>
                </a>
            </li>
<?php
        }
    }

?>

DB.class.php

<?php
class DB {
    // Database configuration
    private $dbHost     = "###";
    private $dbUsername = "###";
    private $dbPassword = "###";
    private $dbName     = "###";
    private $itemTbl    = "###";

    function __construct() {
        if (!isset($this->db)) {
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if ($conn->connect_error) {
                die("Failed to connect with MySQL: " . $conn->connect_error);
            } else {
                $this->db = $conn;
            }
        }
    }

    // Get rows from data table
    function getRows() {
        $query = $this->db->query("SELECT * FROM ".$this->itemTbl." ORDER BY img_order ASC");
        if ($query->num_rows > 0) {
            while ($row = $query->fetch_assoc()) {
                $result[] = $row;
            }
        } else {
            $result = FALSE;
        }
        return $result;
    }
3
  • what is the question ? Commented Jul 6, 2018 at 13:22
  • I would recommend the check_status.php to return a JSON response, like something like this [ {"id":0,"name":"..."}, {"id:... ] instead of returning an HTML response. Then in AJAX success function you could do something like this: var array = JSON.parse(result2); for ( var i=0; i < array.length; i++) { $('#div2').append("<li id=.....") }, then you could save the array and compare the old array to the new array so see what has changed. Commented Jul 6, 2018 at 13:26
  • Thanks for this advice. I will look into coding this Commented Jul 6, 2018 at 13:30

1 Answer 1

2
  1. send ajax request to server each some second
  2. respond json-formatted data, not html from your server controller
  3. if this is first request, save it into "current" and "previous" variables
  4. if this is not first request, save it into "current" variable
  5. Display your data in your html page. During this operation compare "current" and "previous" variables, if something new in "current" highlight it
  6. before next request to server, make assignment: previous = current
  7. profit

Try to search and read something like "create REST service php". You should get main idea of such approach. Generally, your code should look like this:

php.php

<?php
$yourDatabaseClass = new YourDatabaseClass("localhost", "username", "password", "database");
$data = $yourDatabaseClass->getTable("select * from table");
echo json_encode($data);

Your js:

var oldData = [];
var currentData = [];
var yourElement = document.getElementById('application');
client.doRequest("php.php").then(function(response){
   currentData = response;
   renderData();
})
function renderData() {
   yourElement.innerHTML = '';
   currentData.forEach(function(item){
       if(isNew(item)) {
          yourElement.apendChild(createHighlightedData(item));
       } else {
          yourElement.apendChild(createOrdinarData(item));
       }
   })
}
function createHighlightedData(item) {
   return ...
}
function createOrdinarData(item) {
   return ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this advice. I will look into coding these 6 steps. Up to now I've always used PHP and MySQL for database requests but I'm new to using AJAX too, any tutorial posts you can recommend that I read?
Brilliant, Thank You !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.