Getting the unique identifier of a newly generated object using AJAX post request

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)
        }
    })
}

Answer №1

Make a few adjustments to your functions:

function updateFriendList(formData){
    ...
    <td><button type="button" class="delete-friend" name="delete-friend" onclick="deleteFriend(event,'${items["id"]}')">Delete</button></td>
    ...
}

function deleteFriend(e,id){
    e.preventDefault();
    ...
}

You can remove the document.querySelector('tbody') section entirely.

What we're doing here is assigning an onclick attribute to the button to execute the deleteFriend function directly.

Update: Integrated preventDefault directly into the deleteFriend function to stop form submission.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bootstrap button statuses confirmed

I am trying to implement a checked state for group checkboxes in Bootstrap 3.0.2. documentation This is the HTML code snippet: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-default"> <input type="check ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

When an href is clicked in an HTML table, I am interested in fetching the value of the first column row

When a user clicks on the "Edit" link in each row, I want to display an alert with the value of the first column in that row. For example, if I click on the "Edit" link in the first row, I should see an alert with the value of the first column in that row. ...

Deciphering unconventional JSON formats

Can anyone identify the format of this JSON (if it even is JSON!) from the code snippet below? I've extracted this data from a website's HTML and now I'm struggling to parse it in C# using a JSON parser. The data requires significant preproc ...

How to Retrieve the Absolute Index of the Parent Column Using jQuery Datatables

I recently developed a custom column filtering plugin for datatables, but I've encountered a minor issue. Within each column footer, I have added text inputs, and now I am trying to capture their indexes on keyup event to use them for filtering. In ...

Encountering difficulty when trying to define the onComplete function in Conf.ts. A type error is occurring, stating that '(passed: any) => void' is not compatible with type '() => void'.ts(2322)'

I have been developing a custom Protractor - browserstack framework from the ground up. While implementing the onComplete function as outlined on the official site in conf.ts - // Code snippet to update test status on BrowserStack based on test assertion ...

How can I use jQuery to save different types of files like pictures and PDFs as 'mediumblob' in a MySQL database?

I am currently developing a tool for assessments and have encountered an issue with the logic: Whenever I click on 'Upload/View Files' within each question, a modal window pops up; Within the modal window, there is a section where you can s ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

The hyperlink activation event is malfunctioning

There seems to be an issue with the "Goods" link not working after clicking on "Shops." <div class="i_find"> <div class="replaced_link">Goods</div> <div class="link_container"><a href="#" class="a_shops">Shops</a&g ...

Is it a common issue for links to not work on the first click after ajax loads the page?

I've implemented a search box drop-down menu, and everything seems to be working well. However, I've noticed that the links are not functioning properly on the first click. I have to click somewhere else on the body before I can click on the link ...

Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to ...

What is the best way to utilize AJAX to send a value from a foreach loop in Laravel?

I'm encountering an issue where all forms are sending the value as if it's from the first form, however, my intention is for each form to send the data inside it when I press the send button. Blade @foreach($car_lists as $car_list) <li class= ...

Navigating with Vue Router: Automatically redirecting to the homepage upon completion of registration

I have successfully completed the creation of the user registration form. Once the sign-up process is finished, my goal is to have the page redirect back to the home page. I have now integrated vue-router using the vue CLI command. Initially, I tried pl ...

Ensure that the callback response in the $.ajax() function is treated as JSON dataType

My code snippet: <script> $('#email').on('blur', function(){ email = $(tihs).val(); $.ajax({ type: "POST", url: "ajax.php", data: { 'email': email, ...

Troubleshooting problems with Jquery qtip ajax

I am currently attempting to send the value of an input box (specifically an IMDb link) to my imdbgrabber.php page in order to retrieve information about that movie and display it in a qtip box. EDIT: You can view the issue here. Hover over the images to ...

Maximizing the efficiency of threejs through combining and selecting items

In my exploration of three.js optimization, I discovered that reducing the number of draw calls is crucial for improving performance. One way to achieve this is by consolidating geometries through the use of GeometryUtils.merge. Although this optimization ...

Issue with displaying the file-field in Django admin after upgrading from Django 2.1 to version 3

Since upgrading from Django 2.1 to 3, the file field in Django admin is now displaying as "loading". https://i.sstatic.net/8JDWu.png An error is appearing in the console. https://i.sstatic.net/RCgwt.png https://i.sstatic.net/78YtG.png Previously, ther ...

"What is the best way to eliminate duplicate data from an ng-repeat loop in AngularJS

I have a query regarding appending data from the second table into $scope.notiData in AngularJS. Additionally, I need to figure out how to remove ng-repeat data when the user clicks on the remove symbol X. I have attempted some code but it is not functioni ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...