1

There is a javascript in my page that loads a PHP script into a div every second. This PHP is supposed to run a SQL query that loads data from a database.

Here is an extract of the PHP

while($row = mysqli_fetch_array($result))
    {
        $starttime = $row['start_time'];
        $module = $row['module'];
        $item = $row['item'];
        echo "<tr>";
        echo "<td>" . $row['start_time'] . "</td>";
        echo "<td>" . $row['module'] . "</td>";
        echo "<td>" . $row['item'] . "</td>";
        echo "<td>" . $row['status'] . "</td>";
        echo "<td>" . $row['accepted'] . "</td>";
        echo "<td>" . $row['end_time'] . "</td>";
        echo "<td><button id='btnaccept' onclick='acceptBtn()'>ACCEPT</button></td>";
        echo "</tr>";

    }

And here is the Javascript

<script>
    var auto_refresh = setInterval(
    (function () {
     $("#dataDisplay").load("updatedb.php"); //Load the content into the div
    }), 1000);
</script>

As you can see, the last table data is a button that runs a Javascript function

 <script>
function acceptBtn() {
    window.alert("Accepted");
}
</script>

But unfortunately, clicking this button won't run the function. Any help would be appreciated

5
  • what is the error in console Commented Apr 26, 2017 at 6:09
  • Is the button inside a <form>? In that case, it will do a submit too. Also, you're echoing an ID with a constant value in a loop; you should look into that.
    – Mr Lister
    Commented Apr 26, 2017 at 6:11
  • 1
    Add the type attribute to your button: type="button". Commented Apr 26, 2017 at 6:15
  • do you actually mean to load the html every second? or just once, as with setTimeout?
    – Todd
    Commented Apr 26, 2017 at 6:17
  • the button is not inside a form. It is just inside a table. The table is reloaded every second Commented Apr 26, 2017 at 6:30

1 Answer 1

1

Try set listener:

echo "<td><button id='btnaccept'>ACCEPT</button></td>";

.

$(document).on('click', '#btnaccept', acceptBtn);

function acceptBtn(event) {
    event.preventDefault();
    window.alert("Accepted");
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.