Unable to update id with JQuery without refreshing the page

ghz 7months ago ⋅ 40 views

I want to implement a function that allows the user to click on a cell and have it dynamically update and add a value into a database. It is working as intended, but I cannot get it to work without refreshing the page or using location.reload()

I want to change the cell with the class = .submitChange (near the bottom)

<tr>
    <th scope='row'><?php echo $row['lastname'] . ", " . $row['firstname']; ?></th>
    <td><?php echo $row['phone']; ?></td>
    <td><?php echo $row['usertype']; ?></td>
    <?php
    foreach ($events_array as $event) { 
        $event_date = $event['date'];
        $employee_id = $row['id'];
        
        // Check if employee has a vacation day
        $vacation_day = false;
        foreach ($vacation_dates[$employee_id] as $vacation_date) {
            if ($vacation_date == $event_date) {
                $vacation_day = true;
                break; 
            }
        }
        
        // Check if employee is working that day
        $sql_check_worker = "SELECT * FROM Workers WHERE employee={$row['id']} AND event={$event['id']}";
        $result_check_worker = $smeConn->query($sql_check_worker);
        if ($result_check_worker->num_rows > 0) { // displays cell color if employee is working or not
            $serverSum++;
            $cellColorId = 'green-cell';
        } else {
            $cellColorId = 'yellow-cell';
        }
        ?>
        <?php if ($vacation_day) { 
            echo "<td class='vacation'></td>"; 
        } else {
            echo "<td id='$cellColorId' class='submitChange' data-eventid='{$event['id']}' data-employeeid='{$row['id']}'></td>";
        }
        ?>
    <?php } ?>
    <td><?php echo $serverSum; ?></td>
</tr>

Here is my jquery:

$(document).ready(function() {
    $('.submitChange').click(function() {
        $cellId = $(this).attr('id');
        $eventId = $(this).data('eventid');
        $employeeId = $(this).data('employeeid');
        if ($cellId === 'green-cell') {
            $action = 'remove';
        } else {
            $action = 'add';
        }
        console.log($cellId)
        $.ajax({
            url:"includes/ajax_request.php",
            method:"POST",
            data:{
                action:$action,
                eventId:$eventId,
                employeeId:$employeeId
            },
            success:function(response){
                if (response === 'removed') {
                    $(this).removeAttr('id').attr('id', 'yellow-cell'); // Remove old ID and set new one
                    alert("Employee has been removed from event!");
                } else {
                    $(this).removeAttr('id').attr('id', 'green-cell'); // Remove old ID and set new one
                    alert("Employee has been added to event!");
                }  
            }
        })
    })
});

If it's relevant, here is my ajax script:

<?php

include("connect.php");
$action = $_POST['action'];
$eventId = $_POST['eventId'];
$employeeId = $_POST['employeeId'];

if ($action === 'remove') {
    $sql = "DELETE FROM Workers WHERE event = $eventId AND employee = $employeeId";
    $smeConn->query($sql);
    echo "removed";
} else {
    $sql = "INSERT INTO Workers (event, employee) VALUES ($eventId, $employeeId)";
    $smeConn->query($sql);
    echo "added";
}

?>

The function is working as intended; the data is being added into my database and the cell is changing colors, however, it only works after I refresh the page.

Answers

The issue you're encountering is likely due to the scope of this within the success callback of the AJAX request. Inside the success callback function, this does not refer to the element that was clicked ($('.submitChange')). To fix this, you can store a reference to $(this) before making the AJAX call and then use that reference inside the success callback. Here's how you can modify your jQuery code:

$(document).ready(function() {
    $('.submitChange').click(function() {
        // Store a reference to $(this)
        var $clickedCell = $(this);

        var $cellId = $clickedCell.attr('id');
        var $eventId = $clickedCell.data('eventid');
        var $employeeId = $clickedCell.data('employeeid');
        var $action = $cellId === 'green-cell' ? 'remove' : 'add';

        $.ajax({
            url: "includes/ajax_request.php",
            method: "POST",
            data: {
                action: $action,
                eventId: $eventId,
                employeeId: $employeeId
            },
            success: function(response) {
                if (response === 'removed') {
                    $clickedCell.removeAttr('id').attr('id', 'yellow-cell'); // Remove old ID and set new one
                    alert("Employee has been removed from event!");
                } else {
                    $clickedCell.removeAttr('id').attr('id', 'green-cell'); // Remove old ID and set new one
                    alert("Employee has been added to event!");
                }
            }
        });
    });
});

In this modified code:

  • I stored $(this) in the variable $clickedCell.
  • I then used $clickedCell inside the AJAX success callback to refer to the element that was clicked.
  • This ensures that $(this) inside the success callback refers to the correct element.