I have successfully implemented an AJAX post function, but I am facing an issue with the remove button. I need to include the object's ID in the value of the remove button so that my removeFriend function can accurately delete the corresponding row.
function addNewFriend(formData){
const friendForm = document.querySelector('#friend-form');
const nicknameInput = document.querySelector('#id_nick_name');
$.ajax({
type: 'POST',
url: "/friend",
data: formData,
success: function (response) {
// on successful creation of object
// 1. clear the form.
friendForm.reset();
// 2. focus on nickname input
nicknameInput.focus();
// display the new friend in the table.
var instance = JSON.parse(response["instance"]);
var fields = instance[0]["fields"];
const row = document.createElement('tr');
row.innerHTML = `
<td>${fields["nick_name"]}</td>
<td>${fields["first_name"]}</td>
<td>${fields["last_name"]}</td>
<td>${fields["likes"]}</td>
<td>${fields["dob"]}</td>
<td>${fields["lives_in"]}</td>
<td><button type="button" class="remove-friend" name="remove-friend" value="${fields["id"]}">Remove</button></td>
`;
const tbody = document.querySelector('tbody');
tbody.appendChild(row);
},
error: function (response) {
// alert if there is any error
alert(response["responseJSON"]["error"]);
}
})
}
After adding a new friend and seeing it appended at the bottom of the page, trying to remove this friend immediately results in an error. The issue seems to be related to dynamically creating the remove button and assigning its value. Upon inspection in Chrome Elements bar, the value for the remove button of the newly added friend is "undefined." I attempted setting the value to ${instance["id"]}
, but encountered the same problem.
This is the views.py code:
def postFriend(request):
if request.is_ajax and request.method == "POST":
form = FriendForm(request.POST)
if form.is_valid():
instance = form.save()
ser_instance = serializers.serialize('json', [ instance, ])
return JsonResponse({"instance": ser_instance}, status=200)
else:
return JsonResponse({"error": form.errors}, status=400)
return JsonResponse({"error": ""}, status=400)
Is there a way to obtain the object ID of the newly created friend so that the value of the remove button can be correctly set?
Addition as requested: removeFriend function
document.querySelector('tbody').addEventListener('click', function(e){
if(e.target.innerHTML == 'Remove'){
e.preventDefault();
console.log("Remove friend btn clicked?");
console.log(e.target.value);
removeFriend(e.target.value)
}
})
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="${id}"]`);
console.log(row);
row.remove();
alert('friend has been deleted')
},
error: function(xhr, errmsg, err) {
console.log(error)
}
})
}