0

I have a function which generates an html table of Users of the application. Every table row has an action option to EDIT or DEACTIVATE the user. This is all done by AJAX.

It looks like

<tr><td><a id='edit_link' href=''>Edit</a></td></tr>

It is appended by JQuery in an existing html table

So here's what I did.

function loadAllUsersToTable(){
    $.ajax({
        url: 'controller/get_all_users.php',
        type: 'POST',
        dataType: 'json',
        success: function(userData){
            console.log(userData);
            var len = userData.length;
            $('#table_users_record').find("tr:not(:first)").remove();
            for (var i = 0; i < len; i++) {
                var userId = userData[i]['id'];
                var userName = userData[i]['username'];
                var lastName = userData[i]['lastname'];
                var firstName = userData[i]['firstname'];
                var middleInitial = userData[i]['middleinitial'];
                var roleName = userData[i]['roleName'];
                var isActive = userData[i]['isactive'];
                $('#table_users_record').append(
                    "<tr><td>" + userId + "</td>" +
                    "<td>" + roleName + "</td>" +
                    "<td>" + userName + "</td>" +
                    "<td>" + lastName + "</td>" +
                    "<td>" + firstName + "</td>" +
                    "<td>" + middleInitial + "</td>" +
                    "<td>" + isActive + "</td>" +
                    "<td>" + "<a id='edit_link' href=''>" + "Edit" +"</a>" + "</td>" +
                    "<td>" + "<a id='' href=''>" + "Deactivate" +"</a>" + "</td>" +
                    "</tr>"
                );
                $('#edit_link').click(alert("test")); //alert() executes everytime a row data is appended to table.
            }
        },
        error: function (x, e) {
            if (x.status == 0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status == 404) {
                alert('Requested URL not found.');
            } else if (x.status == 500) {
                alert('Internal Server Error.');
            } else if (e == 'parsererror') {
                alert('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknown Error.\n' + x.responseText);
            }
        }
    });
}

My goals are:

  1. Display a Modal Div when EDIT link is clicked. (I tried, but can't get it right)

  2. Pass the User id and/or other User attributes via the <a> tag (I have no idea yet how to do this)

Problem with line $('#edit_link').click(alert("test")); is that it executes everytime a row is rendered or prepared in DOM and not when the link is clicked. It's supposed to execute only when the link is clicked.

How can I go about achieving them?

I'd appreciate any suggestion.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
heisenberg
  • 1,784
  • 4
  • 33
  • 62

2 Answers2

1

That's a function assignment. Replace:

$('#edit_link').click(alert("test"));

With:

$('#edit_link').click(function () {
  alert("test")
});

But ultimately, I would suggest you to look at Event binding on dynamically created elements?. This is the right way to go.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • Thanks for this. This partially solved the problem. The `alert()` message executes when I click the EDIT link but when I click EDIT once, the `alert()` shows X times where X is equal to no. of rows instead of displaying the `alert()` once. Can you help? – heisenberg May 17 '18 at 14:12
  • 1
    @jordan I really need a working [mcve] to help you with this issue. Have you hosted it somewhere? And please make sure you aren't repeating the same `id`. – Praveen Kumar Purushothaman May 17 '18 at 14:14
  • I'm sorry I didn't notice the `id` It should've been a `class` Okay, I'll try to work on the suggestions. Thanks – heisenberg May 17 '18 at 14:19
1

The id edit_link needs to differ. You cant reuse it. Just add the user id to it.

I would recommend using a class (e.g. edit) on all edit buttons and do the click event binding after the for loop.

"<a id='edit_link" + userId + "' class='edit' href=''>Edit</a>"

And the event binding

$('.edit').click(function(ev){
    ev.preventDefault();
    //do something with click

});
Domenik Reitzner
  • 1,583
  • 1
  • 12
  • 21