Home » Jquery » jquery – Passing html parameter to ajax request using 'this' keyword

jquery – Passing html parameter to ajax request using 'this' keyword

Posted by: admin February 22, 2020 Leave a comment


I have small problem:
At start – my sources: users.js

function getUsers(){
    $list = $('.table tbody');
        url: 'http://localhost:8080/user',
        dataType: 'json'
        .done((res) => {
            $.each(res, function (i, item) {
                $list.append('<tr>' +
                    '<th scope="row" >' + res[i].id + '</th>' +
                    '<td>' + res[i].firstname + '</td>' +
                    '<td>' + res[i].lastname + '</td>' +
                    '<td>' + res[i].email + '</td>' +
                    '<td><button class="btn btn-danger btn-xs btn-delete" onclick="deleteUser()" id='+res[i].id+'>Delete</button></td>' +
function deleteUser(){
    let id = this.id;
    let row = $(this);
        url: 'http://localhost:8080/user/'+id,
        type: 'DELETE',
        dataType: 'text',
        success: function(result) {
            alert('user: '+id+' deleted');
        error: function(result) {
            alert('cannot delete user: '+id);

and users.html:

<html lang="en">
    <link rel="stylesheet" href="../../../js/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/main.css">
    <script src="../../../js/jquery-3.4.1.min.js"></script>
    <script src="../../../js/bootstrap.min.js"></script>
    <script src="../../../js/admin/users.js"></script>
    <title>Admin: users page</title>
<div id="wrapper">

    <!-- Sidebar -->
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand">
                <a href="#">
                <a href="/users">Users</a>
                <a href="../index">Log out</a>
    <!-- /#sidebar-wrapper -->

    <!-- Page Content -->
    <div id="page-content-wrapper">
        <button class="button" id="getUsers" onclick="getUsers()" type="button">Get users</button>
        <table class="table">
                <th scope="col">id</th>
                <th scope="col">First</th>
                <th scope="col">Last</th>
                <th scope="col">Mail</th>
    <!-- /#page-content-wrapper -->


Ok, this is my problem:
I click on getUsers button on my page, now I have list of users with delete button on each row.
Now I want to send delete request to user/{id} endpoint with id passed from html row (which contains clicked delete button).
Do You know how to properly pass user id to ajax request after delete button click?
Now I have : let id = this.id; , but id in this situation is undefined

How to&Answer: