-1

The code is supposed to fetch the query result and display it according to the number written in the text box, i tried (onkeydown and onkeyup) and both didn't work, i have no idea why it is not working and what is my mistake.

HTML code:

<script>
        function showRoom(rid) {
            xmlhttp = new XMLHttpRequest();

            xmlhttp.open("GET", "getRoomAJAX.php?q="+rid, true);
            xmlhttp.send();

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                }
            }
        }
    </script>

    <form> 
        <input type="text" name="rid" onkeydown="showRoom(this.value)">
    </form>

    <div id="txtHint">Room...</div>

getRoomAJAX.php code:

<?php
session_start();
ob_start();

$q = $_GET["q"];

$db = new Database();
$dbc = $db->getConnection();

if (!$dbc) {
    die('Could not connect: ' . mysql_error());
}

$query = "SELECT * FROM indvProj_room WHERE rid = '".$q."'";

$result = mysqli_query($dbc, $query);

//start creating the table HTML
if ($result) {
    echo "<table border='1' align='center' cellspacing = '2' cellpadding = '4' width='100%'>
          <tr>
          <th><b>Room ID</b></th>
          <th><b>Room Description</b></th>
          </tr>";
    while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
        echo "<tr>";;
        echo "<td>" . $_SESSION['adminRoomChoice'] = $row['rid'] . "</td>";
        echo "<td>" . $row['roomDesc'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo '<p class="error">Sorry, cannot find the room, are you sure of the entered Room ID?</p>';
    echo '<p class = "error">' . mysqli_error($dbc) . '</p>';
}


?>
  • You have an error. [`mysql_error()`](https://www.php.net/manual/en/function.mysql-error.php) worked only for the old API. Please consider switching error mode on instead. [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Jun 12 '20 at 20:09

1 Answers1

0

Does showRoom() get called at all? Put a console.log(rid); inside showRoom() to see if that is getting called and whether the value is being passed in correctly.

If you can determine that it's getting into the showRoom(), then follow the code down and into PHP to see where it's failing. Echo some sample text at the top of the PHP file with return; right below it. That will tell you if the error is in the XMLHttpRequest code or somewhere in the PHP file.

Normally, I don't pass any variables/params with onkeydown type of events. Usually, I call a method like this without params and then retrieve the value based on the element's id. See this answer for more detail on that: https://stackoverflow.com/a/54040431/3103434

Spudly
  • 310
  • 1
  • 2
  • 10