I am working on a website that has a feature to add and remove friend I wanted to make AJAX requests to add & remove a friend from user DB
here is my client-side JS code
window.addEventListener('DOMContentLoaded', (event) => {
var username = document.getElementById("profileUsername").innerHTML;
if(document.getElementById("addFriend")!= null){
document.getElementById("addFriend").onclick = () => {
$.ajax(
{
url : '/add_friend_JSON/'+username ,
method : 'GET' ,
processData: false,
contentType: false,
success: function(status) {
if ( status["status"] == 0 ) {
document.getElementById("addFriend").innerHTML = "Unfriend";
document.getElementById("addFriend").setAttribute("id" , "unFriend" );
}
}
})
return false;
}
}
else {
document.getElementById("unFriend").onclick = () => {
$.ajax(
{
url : '/remove_friend_JSON/'+username ,
method : 'GET' ,
processData: false,
contentType: false,
success: function(status) {
if ( status["status"] == 0 ) {
document.getElementById("unFriend").innerHTML = "Add Friend";
document.getElementById("unFriend").setAttribute("id", "addFriend");
}
}
})
return false;
}
}
});
the above basically is like a switch which flips when we click it be 'add friend' and 'unfriend'
but the problem is it working only one time like if id changes from and friend to unFriend The next time when I click it without reloading the page, I got the following error in the log window
Uncaught TypeError: Cannot set property 'innerHTML' of null
at Object.success (profile.js:36)
at c (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at l (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
here my HTML for reference
<button type="submit" class="btn btn-warning d-btn" id = "addFriend">
Add Friend
</button>
The backend code just updates the DB based on the request Thank you!