3

I'm creating a web application in both html, php, and jquery/javascript and I need it to be "live updating". I have gotten the fetching of the database working just fine with jquery. Look at the code below

while ($row = mysqli_fetch_array($r)) {
    echo "<tr><td>".$row['id']."</td>";
    echo "<td>".$row['callsign']."</td>";
    echo "<td>".$row['service_id']."</td>";
    ?>
    <td>
        <select style="width: 150px;" id="status" name="status" class="form-control form-control-sm" onchange="this.form.submit();">
            <optgroup label="NÅVÆRENDE STATUS">
                <option disabled selected="true" value="<?php echo($row['status']) ?>"><?php echo $row['status']; ?></option>
            </optgroup>
            <optgroup label="SETT NY STATUS">
                <option style="color:green;font-weight:bold;" value="LEDIG">LEDIG</option>
                <option style="color:red;font-weight:bold;" value="OPPTATT">OPPTATT</option>
                <option style="color:red;font-weight:bold;" value="99">99</option>
            </optgroup>
            <optgroup label="AV VAKT">
                <option style="color:red;font-weight:bold;" value="avVakt">AV VAKT</option>
            </optgroup>
        </select>
    </td>
    <?php
    #echo "<td>".$row['status']."</td>";
    echo "<td contenteditable='true'></td></tr>";
}

The table is updated every 5 seconds, and it works just fine, using this code

  $(document).ready(function(){
    function loadUnits(){
      if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
      } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("unitlist").innerHTML = this.responseText;
        }
      };
      xmlhttp.open("GET","inc/ops/getunitlist.php",true);
      xmlhttp.send();
    }
    loadUnits();

    setInterval(function() {
      loadUnits()
    }, 5000);
  });

What my problem is, is that I'm using the dropdown as a form, to post new data to the database when clicked. But every time the table is updated, if the dropdown is open, it gets closed, probably because it's loading all over again. Is there any way I can avoid this? I'm also open to use Ajax if possible.

Thanks!

Jesper
  • 33
  • 4
  • 1
    This line `document.getElementById("unitlist").innerHTML = this.responseText;` makes the browser to re render the entire table including all the `` elements every time this line will run, however you can save the selected option for each `` elements check [this](https://stackoverflow.com/q/249192/5407848). – Accountant م Aug 18 '19 at 00:45
  • 3
    A possibly better option is to request only the necessary data that needs to be updated as JSON and skip replacing the entire HTML. – Accountant م Aug 18 '19 at 00:45

0 Answers0