heisenberg
heisenberg

Reputation: 1954

Applying click action on html table generated by AJAX call

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.

Upvotes: 0

Views: 98

Answers (2)

Domenik Reitzner
Domenik Reitzner

Reputation: 1613

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

});

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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.

Upvotes: 1

Related Questions