[SOLVED] Why does the button inside of an ajax result in JQueryUI Dialog doesn’t fire when clicked?

Issue

This Content is from Stack Overflow. Question asked by Kim Taeha

So I created a JQuery dialog and gets its content (table) using ajax.
The table includes all columns from DB and I added a button in each row which has its id (from database) that corresponds when clicked it will show me the full details. The problem is, the buttons on every row of the table doesn’t respond at all even for a simple js alert it doesn’t show any.

$(".view-table-btn").on( "click", function() {
    var group_id = $(this).attr('data-group_id');
    $.ajax({
        type: "POST",
        data:{
            search:"table",
            group_id:group_id,
        },
        url: "./function/view_group-table.php",
        success: function (table_data) {
            $("#group-attr_table").dialog( "open" );
            $('#group-attr_table').empty();
            $('#group-attr_table').append(table_data);
        }
    });
});

$( "#group-attr_table" ).dialog({
    autoOpen: false,
    resizable: false,
    width:800,
    height:600,
    modal: true,
    draggable: false,
    show: {
        effect: "fold",
        duration: 500
    },
    hide: {
        effect: "slide",
        duration: 500
    },
});
 // Here is the code for the button onclick on the ajax table inside of a dialog 
$(".user_details").on( "click", function() {
    var id = $(this).html();
    alert(this);
    console.log(id);
});



Solution

I’m not sure what table_data contains, but I’ll assume that are objects with the class attribute .user_details. In that case, since the AJAX call is asynchronous, you are assigning the click behavior before the objects exist in the DOM. I would recommend you assign the click event trigger when you fill out the table:

$(".view-table-btn").on( "click", function() {
    var group_id = $(this).attr('data-group_id');
    $.ajax({
        type: "POST",
        data:{
            search:"table",
            group_id:group_id,
        },
        url: "./function/view_group-table.php",
        success: function (table_data) {
            $("#group-attr_table").dialog( "open" );
            $('#group-attr_table').empty();
            $('#group-attr_table').append(table_data);
            $(".user_details").on( "click", function() {
                var id = $(this).html();
                alert(this);
                console.log(id);
            });
        }
    });
});

$( "#group-attr_table" ).dialog({
    autoOpen: false,
    resizable: false,
    width:800,
    height:600,
    modal: true,
    draggable: false,
    show: {
        effect: "fold",
        duration: 500
    },
    hide: {
        effect: "slide",
        duration: 500
    },
});

Hope it helps


This Question was asked in StackOverflow by Kim Taeha and Answered by dubafek It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?