1

I am querying and displaying list of posts which also have buttons. I am trying to get the button ID when clicked. Its running on console but failing from editor.

php: testDisplay.php

include('../../common/database.mysqli.php');

        $conn = new common();
        // $page= $_POST["page"];

        $query = $conn->get_query("SELECT * FROM test_posts");
        $count = $conn->find_no_rows($query);
        $output .= '<ul id="inserted-data">';
        if ($count > 0) {
            while ($results = $conn->fetch_assoc_array($query)) {
            $output .= '<li class="data-list">'. $results['post'] .'
                                        <button class="data-delete" id="del-'. $results['id'] .'">Delete</button>
                                        <button class="data-update" id="edit-'. $results['id'] .'">Update</button>
                                    </li>';
            // echo $results['id'];                     
            }
            $output .= '</ul>';
        }
        
        echo $output;
        //inserting this ul inside other class through jQuery below

jQuery: this is bringing php data and loading through ajax `

function loadPost(page){
        $.ajax({
            url: "include/testDisplay.php",
            method: "POST",
            data: {page:page},
            success: function (data) {
                $('.other').html(data);
            }
        });
        
    }
    loadPost();

;`

this gives me ID in console but failing in editor -

$(".data-delete").bind('click', function(){
            console.log(this.id);
        })
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Saani Info
  • 67
  • 6
  • What is `in editor`? – user3783243 Nov 24 '20 at 13:14
  • Hi, this `data-delete` is dynamically generated so you need to bind it with static parent ..i.e : `$(document).on("click",".data-delete",function(){ //you codes })` .Also have a look at [this](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) post . – Swati Nov 24 '20 at 13:19
  • The problem description is a bit hard to understand here, but I’m guessing this is just the usual problem, of “statically” bound event handlers not applying to elements, that have been added to the document later. And the general solution for that is called _event delegation_, so go and read up on that. – CBroe Nov 24 '20 at 13:19
  • @Swati Thanks, It worked. For any dynamically generated element we need it grab it by `$(document)` ? – Saani Info Nov 24 '20 at 13:41
  • @user3783243 i mean from local `code` editor. – Saani Info Nov 24 '20 at 13:45
  • It can be any element which is already present in your `DOM` i.e : `body,any div..etc` .Go through link which i have added in my previous comment to know more . – Swati Nov 24 '20 at 13:46

0 Answers0