HTML button onclick property does not call the function, behaving strangely when changed


I am making an app that procedurally generates HTML code from MySQLi database results. It uses a button that calls a JavaScript function that sends an XMLHttpRequest to the server that deletes the row to remove items from the list once they have been processed.
Here is the relevant PHP code:


$conn = new Conn();
$result = $conn->query("SELECT * FROM orders");

<?php foreach($result as $item) {?>
    <div class="row" id="item<?php echo $item['oid']; ?>">
        <span class="item"><?php echo htmlspecialchars($item['a']); ?></span>
        <span class="item"><?php echo htmlspecialchars($item['b']); ?></span><br>
        <button type="button" onclick="close('<?php echo $item['c']; ?>')">Item processed</button>
<?php }?>
<script src="js/dashboard.js"></script>

And here is dashboard.js:

function close(order_id) {
    console.log("Closing order number " + order_id);
    var http = new XMLHttpRequest();
    http.onreadystatechange = function() {
        console.log("Readystate changed! New: " + this.readyState);
        if (this.readyState == 4 && this.status == 200) {
            console.log("Operation completed.");
            document.getElementById("order" + order_id).remove();
    }"GET", "order_complete.php?oid=" + order_id, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

However, the problem is that onclick does not call the close function. In the inspect element panel, it shows up correctly as <button type="button" onclick="close(2)")>Item processed</button>. but, when I click the button, nothing happens. I have tried:

  • Explicitly declaring the button as a button using type="button". Made no difference.
  • Removing the parameter from the onclick tag so it looked like onclick="close(1)". Made no difference.
  • Removing all styling from the button. Made no difference.
  • Calling the function from the console. It worked there, and removed the item from the page. So it seems the button is the problem.
  • Changing the onclick of the button from the inspect panel to alert("Hi"). The function called when the button was pressed. When I changed it back to close(2) it called alert("Hi") again.


Solved: Aparrantly close() is a reserved function.
Changing it to closeOrder() fixed the issue.

Answered By – Michael Rothkopf

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published