Skip to content
Advertisement

Why i am not able to fetch table data in AJAX ? Everytime i fetch req_id from table it’s gives me undefined value in Console.log

I want to take req_id but everytime i fetch req_id from table it’s gives me undefined in Console.log().Please see in table data req_id and yes the databse connection is okay i can see the value.I tried this both GET and POST method but still i get the same error.All i want is fetch req_id and show it in console.log as defined value

Thank You

<!-- main  -->
<section class="pad-70">
    <div class="container">
        <p id="demo"></p>
        <?php
        $userQuery = $connection->Show($conobj, "requested_car");
        if ($userQuery->num_rows > 0) {
            echo "<table><tr><th>Req ID</th><th>Action</th></tr>";
            // output data of each row
            while ($row = $userQuery->fetch_assoc()) {
                echo "<tr ><td id=req_id>";
                echo (htmlentities($row['req_id']));
                echo ("</td><td>");
                echo ('<button onclick="confirmcar()" class="btn btn-lg btn-success">Confirm</button> <button onclick="MyAjaxFunc()" class="btn btn-lg btn-danger">Cancel</button>');
                echo ("</td></tr>n");
            }
            echo "</table>";
        } else {
            echo "0 results";
        }
        $connection->CloseCon($conobj);
        ?>
    </div>
</section>
<!-- main  -->

<script>
function confirmcar() {

    var req_id = document.getElementById("req_id").value;
    console.log(req_id);


}
</script>

Advertisement

Answer

So, going from your last edit, I removed the PHP and tried to simulate the HTML that would be generated with several rows.

Now several points remained:

  1. You have missing quotes around your attribute value req_id, as in id="req_id". (Not a real issue as @Quentin pointed out on another answer, but let’s keep things tidy for the sake of our eyes)
  2. You’re setting event handlers using on... html attributes, which is bad practice. Doing it with js addEventListener will help a lot solving your problem as you’ll see below.
  3. One of your problems is that you don’t set a different id at each row for your <td>. If your ids are repeated, it probably means you should use a class instead. And setting different ids could have eased the process of selecting the right one on click. But it’s not fatal so we’ll go from here.

The code snippet below illustrates how you should proceed to get the value which is the inner text of the <td> with id “req_id” on the table row where the “Confirm” button was clicked:

  • Add an event listener for each of these buttons, and when a button’s clicked:
  • climb up the DOM until you hit its parent <tr>
  • within this row, find the <td id="req_id"> by its id
  • read its innerText property

//When the DOM is fully loaded
window.addEventListener('DOMContentLoaded', _e => {
  //Find all buttons with class btn-success
  const buts = document.querySelectorAll('.btn-success');
  //Add a click handler to each one
  buts.forEach(button => {
    //When the button's clicked
    button.addEventListener('click', e => {
      //Find parent <tr>
      const tr = button.closest('tr');
      //Find child with id req_id and get its text
      const val = tr.querySelector('#req_id').innerText;
      console.log(val);
    });
  });
});
<section class="pad-70">
    <div class="container">
        <p id="demo"></p>
          <table>
            <tr>
              <th>Req ID</th><th>Action</th>
            </tr>
            <tr>
              <td id="req_id">My Value 1</td>
              <td>
                <button class="btn btn-lg btn-success">Confirm</button>
                <button class="btn btn-lg btn-danger">Cancel</button>
              </td>
            </tr>
            <tr>
              <td id="req_id">My Value 2</td>
              <td>
                <button class="btn btn-lg btn-success">Confirm</button>
                <button class="btn btn-lg btn-danger">Cancel</button>
              </td>
            </tr>
            <tr><td colspan="100">...</td></tr>
          </table>
    </div>
</section>

I’m using event window.DOMContentLoaded in order for my script to fire only after the DOM has been fully parsed from HTML. Else the buttons would not exist yet when trying to assign event handlers to them.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement