3

I have a PHP file which displays data from a database. I'm using while() to display each of the records.

My PHP file:

<?php

    $flightTicketsSQL = "SELECT * FROM `flightbookings` WHERE username='$user' AND cancelled='no'";
    $flightTicketsQuery = $conn->query($flightTicketsSQL);

    while($flightTicketsRow = $flightTicketsQuery->fetch_assoc()) { ?>

    <tr>
        <td class="tableElementTags text-center"><?php echo $flightTicketsRow["bookingID"]; ?></td>
        <td class="tableElementTags text-center"><?php echo $flightTicketsRow["origin"]; ?></td>
        <td class="tableElementTags text-center"><?php echo $flightTicketsRow["destination"]; ?></td>
        <td class="tableElementTags text-center"><?php echo $flightTicketsRow["date"]; ?></td>
        <td class="tableElementTags text-center"><?php echo $flightTicketsRow["mode"]; ?></td>
        <td class="text-center"><span class="fa fa-remove tableElementTags pullSpan" id="deleteAccount"></span></td>
    </tr>

<?php } ?>

If the user clicks on the last <td> (the one with the Font Awesome icon), I want the record with the particular bookingID be deleted from the database.

To do this I'll need to identify the value using jQuery .val()

My JS file:

var id = $("**WHAT DO I PUT HERE ?**").val();

    $('#deleteAccount').click(function() {
        $.ajax({
            type: "POST",
            url: 'cancelTicket.php',
            data: { bookingID : id },
            success : function() {
                alert("Cancelled");
            }
        });
    });

My cancel.php file:

<?php

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "database";

    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $user = $_SESSION["username"];
    $id = $_POST["bookingID"];


    $cancelFlightBookingsSQL = "UPDATE `flightbookings` SET cancelled='yes' WHERE bookingID='$id'";
    $cancelFlightBookingsQuery = $conn->query($cancelFlightBookingsSQL);

My question is how do I make jQuery identify which booking the user wants to be cancelled? I mean how do I assign an id to the <td> so that I can retrieve its value in the JS.

I know I could not frame this question properly. SORRY ABOUT THAT.

Thanks

11
  • Where is the id="deleteAccount" element that's actually being clicked? Commented Oct 4, 2017 at 14:36
  • 1. You have no #deleteAccount element. 2. Make sure that you're not duplicating that id on each row. 3. Get the id from the button within the click handler using the this reference to get the clicked element Commented Oct 4, 2017 at 14:39
  • @David It'll be in the <span class="fa fa-remove tableElementTags pullSpan"></span>. I've not added it. I'll edit the question and add it. Commented Oct 4, 2017 at 14:40
  • Which td holds the value which should be sent in the request? Commented Oct 4, 2017 at 14:42
  • 1
    @Samuel don't do that. on* attributes are an anti pattern which should be avoided. Use an unobtrusive event handler. Commented Oct 4, 2017 at 14:45

2 Answers 2

3

There's a couple of issues here. Firstly you need to use a class for the span instead of an id, otherwise it will be duplicated in the DOM by your PHP loop, which will result in invalid HMTL that will break your click event handler.

Once you've done that you need to set the id variable value within the click handler so that you can find the td related to the clicked element. You can do that like this:

<!-- repeated throughout your while loop -->
<td class="text-center">
  <span class="fa fa-remove tableElementTags pullSpan deleteAccount"></span>
</td>
$('.deleteAccount').click(function() {
  var id = $(this).closest('tr').find('td:first').text().trim();

  $.ajax({
    type: "POST",
    url: 'cancelTicket.php',
    data: {
      bookingID: id
    },
    success: function() {
      alert("Cancelled");
    }
  });
});
Sign up to request clarification or add additional context in comments.

17 Comments

Thanks. I'll try it out and let you know.
Can you give any more information, as that's not really enough to debug. Are there any errors in the console? Are you running the jQuery code in a document.ready event handler?
No errors. Nothing. The code just doesn't run. The data is not updated in the DB.
If you check the network tab of the console can you see the request being made? If so, what's the response text and status code?
Sorry if I'm being dumb, but where's the network tab? I'm very very new to these things.
|
2

From the clicked element:

$('#deleteAccount').click(function() {

You can navigate the DOM to find the element you want. First, add a class to that target element:

<td class="tableElementTags text-center bookingID"><?php echo $flightTicketsRow["bookingID"]; ?></td>

Next, also put that Booking ID value in a data attribute for easy programmatic access (personal preference, since things like text content can easily change):

<td class="tableElementTags text-center bookingID" data-booking="<?php echo $flightTicketsRow["bookingID"]; ?>"><?php echo $flightTicketsRow["bookingID"]; ?></td>

Now from within the click handler you can navigate up the DOM to the closest common parent element and then back down to the target element with the data you want. Something like this:

$('#deleteAccount').click(function() {
    var id = $(this).closest('tr').find('.bookingID').data('booking');
    // the rest of your click handler
});

1 Comment

Thanks. I'll try it out and let you know.

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.