简体   繁体   中英

Using AJAX for query to MySQL database

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;
    }
  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 ...
}

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