Search code examples
javascriptdjangoajaxdom-manipulation

Removing an object from database and the DOM via AJAX


So I have this simple AJAX post request that is deleting the object from the Model as I want it to but I am struggling to delete it from the DOM correctly.

function removeFriend(id){

    let dataId = `${id}`

    $.ajax({
        type: 'POST',
        url: `/delete/friend`,
        data: {
            friend_id: `${id}`,
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
            action: 'post'
        },
        success: function(json){
            let tbody = document.querySelector('tbody');
            let row = tbody.querySelector('tr[data-id=dataId]');
            console.log(row);
            row.remove();
            alert('friend has been deleted')
        },
        error: function(xhr, errmsg, err) {
            console.log(error)
        }
    })
}

I keep getting index.js:119 Uncaught TypeError: Cannot read property 'remove' of null and the console.log(row) is showing up as null. I have tried let row = tbody.querySelector('tr[data-id=`${id}`]'); and same result.

I have tried let row = tbody.querySelectorAll('tr[data-id=dataId]'); but then the output for console.log(row) is an empty NodeList NodeList [] followed by index.js:119 Uncaught TypeError: row.remove is not a function.

This is what my table looks like:

    <table class="table table-striped table-sm" id="my_friends">
        <thead>
            <tr>
                <th>Nick name</th>
                <th>First name</th>
                <th>Last name</th>
                <th>Likes</th>
                <th>DOB</th>
                <th>lives in</th>
                <th>Remove friend</th>
            </tr>
        </thead>
        <tbody>
        {% for friend in friends %}
        <tr data-id="{{ friend.id }}">
            <td>{{friend.nick_name}}</td>
            <td>{{friend.first_name}}</td>
            <td>{{friend.last_name}}</td>
            <td>{{friend.likes}}</td>
            <td>{{friend.dob | date:"Y-m-d"}}</td>
            <td>{{friend.lives_in}}</td>
            <td><button type="button" class="remove-friend" name="remove-friend" value="{{ friend.id }}">Remove</button></td>
        </tr>
        {% endfor %}
        </tbody>
    </table>

I know I have definitely assigned the data attribute correctly because I can see it showing up in my Chrome browser Elements.


Solution

  • Use the id passed to the remove friend function in the selector

    let row = tbody.querySelector(`tr[data-id="${id}"]`);