2

I am using AJAX to call a PHP file that pulls a summary of calls from a MySQL database. The AJAX routine then inserts the returned table with an HTML form for each row in the table into the original webpage. Each row has a submit button to open the actual record and display all info so it can be edited. When I code this just in HTML without the AJAX update it works perfectly but I need to refresh the webpage to update the data. I want the data refreshed every 5 seconds automatically without needing to refresh the entire page. When I move the code to the AJAX routine the table pulls in perfectly with the data and the submit buttons for each row but the submit buttons don't do anything.

Code calling AJAX routine in main HTML page

const interval = setInterval(function() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    document.getElementById("unitstatus").innerHTML = this.responseText;
  }
xhttp.open("GET", "updatestatus.php");
xhttp.send(); 
}, 5000);

Code Displaying Response in main HTML page

<div id='unitstatus' name='unitstatus'></div>

PHP File called by AJAX

<?php

session_start();
$event = $_SESSION['event'];

set_include_path('./includes/');
include 'conn.inc';

$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * from sags WHERE Complete='N' AND event='$event' ORDER BY bib";

?>
<!DOCTYPE html >
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
    <table width='100%' border='1'>
        <tr>
            <td width='100%' height='45px' colspan='8' class='w3-center'>
                <button class='w3-button w3-blue w3-text-white w3-medium w3-padding-8' name='addnew' id='addnew' onclick='gotonewcall()'>ADD NEW REQUEST</button>
            </td>
        </tr>
        <tr>
            <td width='6%' class='w3-padding-small w3-small'><b>ID</b></td>
            <td width='14%' class='w3-padding-small w3-small'><b>NAME</b></td>
            <td width='6%' class='w3-padding-small w3-small'><b>BIB</b></td>
            <td width='12%' class='w3-padding-small w3-small'><b>CELL PHONE</b></td>
            <td width='24%' class='w3-padding-small w3-small'><b>CALL</b></td>
            <td width='18%' class='w3-padding-small w3-small'><b>LAST UPDATE</b></td>
            <td width='15%' class='w3-padding-small w3-small'><b>STATUS</b></td>
            <td width='5%'></td>
        </tr>
        <?php
            if(mysqli_query ($conn, $sql)){
            $result = mysqli_query ($conn, $sql);
            while($row=mysqli_fetch_array($result)){
                if ($row['status']=="ONLOCATION"){
                    $status = "ON LOCATION";
                } else {
                    $status = $row['status'];
                }
        ?>
        <form action="editrequest.php" method="post">"
            <tr>
                
                <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['id'] ?><input type='text' name='id' id='id' style='width:100%' class='w3-light-gray' value=<?php echo $row['id'] ?> hidden></b></td>
                
                <td width='14%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['fName'] ?></b></td>
                <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['bib'] ?></b></td>
                <td width='12%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['cellphone'] ?></b></td>
                <td width='24%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['sagrequest'] ?></b></td>
                <td width='18%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['statstime'] ?></b></td>
                <?php
                    if ($status == "ON LOCATION"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-red'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    } elseif ($status == "ENROUTE"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-yellow'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    } elseif ($status == "NEW"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-white'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    } elseif ($status == "RECEIVED"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-gray'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    } elseif ($status == "TRANSPORTING"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-purple'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    }
                ?>
                <td width='5%' class='W3-center w3-tiny'>
                    <input type="submit" value="OPEN" name="editentry" id="editentry" class="w3-button w3-blue w3-center" style="width:100%; height:100%">
                </td>
            </tr>   
        </form>
        <?php
                }
            } else {
                echo "<tr><td colspan='8' class='w3-center'><h3><b>NO ACTIVE CALLS</b></h3></td></tr>";
            }
        ?>
        </table>
        <?php
            mysqli_close();
        ?>
2
  • 1
    It's an outdated principle to go fetch some "HTML" from a server-side-rendered resource. You would be better to fetch some JSON data, and build the HTML from that returned data i.e: on the client. That way you can create a reusable API and don't care for the response markup, but instead you'll know it uses a standardized JSON data. Commented Aug 22, 2021 at 21:59
  • What exactly is not working? What have you tried to make it work? Is this related to JS, PHP, or AJAX? Commented Aug 23, 2021 at 7:36

2 Answers 2

1

I will do something like this, working example here.

PHP file

<?php
    session_start();
    $event = $_SESSION['event'];
    
    set_include_path('./includes/');
    include 'conn.inc';
    
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    $sql="SELECT * from sags WHERE Complete='N' AND event='$event' ORDER BY bib";
                if(mysqli_query ($conn, $sql)){
                $result = mysqli_query ($conn, $sql);
                while($row=mysqli_fetch_array($result)){
                    if ($row['status']=="ONLOCATION"){
                        $status = "ON LOCATION";
                    } else {
                        $status = $row['status'];
                    }
            ?>
            
                <tr>
                    
                    <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['id'] ?>
                     </b></td>
                    
                    <td width='14%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['fName'] ?></b></td>
                    <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['bib'] ?></b></td>
                    <td width='12%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['cellphone'] ?></b></td>
                    <td width='24%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['sagrequest'] ?></b></td>
                    <td width='18%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['statstime'] ?></b></td>
                    <?php
                        if ($status == "ON LOCATION"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-red'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        } elseif ($status == "ENROUTE"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-yellow'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        } elseif ($status == "NEW"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-white'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        } elseif ($status == "RECEIVED"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-gray'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        } elseif ($status == "TRANSPORTING"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-purple'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        }
                    ?>
                    <td width='5%' class='W3-center w3-tiny'>
                        <form action="editrequest.php" method="post">
                        <input type='text' name='id' id='id' style='width:100%' class='w3-light-gray' value=<?php echo $row['id'] ?> hidden>
                        <input type="submit" value="OPEN" name="editentry" id="editentry" class="w3-button w3-blue w3-center" style="width:100%; height:100%">
                     </form>
                    </td>
                </tr>   
            <?php
                    }
                } else {
                    echo "<tr><td colspan='8' class='w3-center'><h3><b>NO ACTIVE CALLS</b></h3></td></tr>";
                }
            ?>

JavaScript

const interval = setInterval(function() {
  $("#tableForm").load("updatestatus.php");//Load since just updating data
//You can use $.get() as well
//Or use $.post() if you have some data to send to php file.
//and append response with .html()
}, 5000);

HTML

<!DOCTYPE html >
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
    <table width='100%' border='1'>
        <tr>
            <td width='100%' height='45px' colspan='8' class='w3-center'>
                <button class='w3-button w3-blue w3-text-white w3-medium w3-padding-8' name='addnew' id='addnew' onclick='gotonewcall()'>ADD NEW REQUEST</button>
            </td>
        </tr>
        <tr>
            <td width='6%' class='w3-padding-small w3-small'><b>ID</b></td>
            <td width='14%' class='w3-padding-small w3-small'><b>NAME</b></td>
            <td width='6%' class='w3-padding-small w3-small'><b>BIB</b></td>
            <td width='12%' class='w3-padding-small w3-small'><b>CELL PHONE</b></td>
            <td width='24%' class='w3-padding-small w3-small'><b>CALL</b></td>
            <td width='18%' class='w3-padding-small w3-small'><b>LAST UPDATE</b></td>
            <td width='15%' class='w3-padding-small w3-small'><b>STATUS</b></td>
            <td width='5%'></td>
        </tr>
        <div id="tableForm"><!-- I will load form here from php --></div>
</table>

Edit:-

Explanation

In the inspect element I saw <form .....> ... but no </form>, I tried lot things to make it a clear defined form but failed. There is some part of your code which is breaking the input element so I declared it separately since the form has only 1 input.

Suggestion

  1. Echo out only the needed code from ajax requested file.
  2. Avoid using <b> why? idk but better use font-weight:bold
  3. Use $.ajax() $.post() $.get() more easy way to AJAX requests.
Sign up to request clarification or add additional context in comments.

2 Comments

Please add some explanation to your answer. What did you change, and why? Keep in mind that an explanation helps others to understand your answer and learn from it
This answer looked a little simpler so I tried it first and it is working perfectly. Thank you!
1

Because you are adding new elements to the DOM, you'll need register event handlers for each new added button.

However there is another method you can use is to register event listener on the table itself only once and capture events originated from buttons:

const templ = document.getElementById("templ").content;
const result = document.getElementById("result");

//event listener on parent
document.getElementById("table2").addEventListener("click", buttonClicked2);

function add(parent, addEvent)
{
  parent = document.getElementById(parent);
  const row = templ.cloneNode(true);
  row.querySelector("td").textContent = "row " + (parent.children.length+1);
  //event listener on button
  if (addEvent)
    row.querySelector("button").addEventListener("click", buttonClicked);

  parent.tBodies[0].appendChild(row);
}

function buttonClicked(e) {
  result.textContent = "table=" + e.target.parentNode.offsetParent.id + " row=" + e.target.parentNode.parentNode.rowIndex;
}

function buttonClicked2(e) {

  result.textContent = e.target.tagName; //this will show which element clicked unless button was clicked

  if (e.target.tagName != "BUTTON")
    return;

  result.textContent = "table=" + e.target.parentNode.offsetParent.id + " row=" + e.target.parentNode.parentNode.rowIndex;
}
.flex {
  grid-gap: 1em;
  display: flex;
}
Clicked button at <span id="result"></span>
<div class="flex">
  <div>Events from button 
    <button onclick="add('table1', true)">Insert</button>
    <table id="table1">
      <thead><tr><th>col1</th><th>col2</th></tr></thead>
      <tbody></tbody>
    </table>
  </div>
  <div>Events from table 
    <button onclick="add('table2', false)">Insert</button>
    <table id="table2">
      <thead><tr><th>col1</th><th>col2</th></tr></thead>
      <tbody></tbody>
    </table>
  </div>
  <template id="templ"><tr><td></td><td><button>click me</button></td></tr></template>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.