1

I would like to display a button id which is getting by ajax response

I getting repose of button using these lines of code

index.php

<script language="JavaScript">
        var XMLHttpRequestObject=false;

        if(window.XMLHttpRequest){
            XMLHttpRequestObject = new XMLHttpRequest();
        }else if(window.ActiveXObject){
            XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHttp");
        }

        function getData(){

            var district_id = 'D01';
            var queryString = "?district_id=" + district_id ;

            XMLHttpRequestObject.onreadystatechange = function(){
                if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
                    var container = document.getElementById('issues');
                    var response = XMLHttpRequestObject.responseText;
                    container.innerHTML = response;
                }
            }
            XMLHttpRequestObject.open("GET", "complaints.php"+queryString ,true);
            XMLHttpRequestObject.send(null);
        }
    </script>

and display the code in these area in the same index.php

<div id="issues">

    </div>

Now I can display the details embedded in this php file (complaints.php)

<?php
$district_id = $_GET['district_id'];
echo '<button id="'.$district_id.'">'.$district_id.'</button>';
?>

Now my issue is I need button id dynamically

Therefore using below jquery I'm trying this code but it does not work

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>        
        $(document).ready(function(){
        getData();
            $("button").click(function(){
                var id = $(this).attr("id");
                alert(id);
            });
    }); 
</script>
it's me
  • 188
  • 1
  • 1
  • 10

1 Answers1

0

Your button is dynamically created from the AJAX response, so you can't attach the click event directly to the button onload because it doesn't exist in the DOM at that time.

Use Event Delegation, and delegate the event to something higher, such as the document. This means all clicks will be checked by the selector passed to .on, so all click events will bubble up and be handled by your function (if it matches the selector).

$(document).on('click', 'button', function(){
    var id = $(this).attr("id");
    alert(id);
});
MrCode
  • 63,975
  • 10
  • 90
  • 112