Search code examples
phpjqueryajax

Unable to update id with JQuery without refreshing the page


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.


Solution

  • As @grumpycrouton mentioned this does not mean what you expect in that context.

    Please try something like this:

    $(document).ready(function () {
    $('.submitChange').click(function (ev) {
        ev.stopPropagation();
    
        var cell = ev.target;
        $cellId = $(cell).attr('id');
        $eventId = $(cell).data('eventid');
        $employeeId = $(cell).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') {
                    $(cell).removeAttr('id').attr('id', 'yellow-cell'); // Remove old ID and set new one
                    alert("Employee has been removed from event!");
                } else {
                    $(cell).removeAttr('id').attr('id', 'green-cell'); // Remove old ID and set new one
                    alert("Employee has been added to event!");
                }
            }
        })
      })
    });