0

I have created a table using an array of JSON Objects that are returned by my servlet. I am trying to make it so that when I click on the image I add before each row it will call a function. The code below should work but it does not and I think I'm missing something simple.

 $(document).ready(function(){
           loadData();
           $("#item").bind("click", function() { alert("test"); });
   });
function loadData(){
    $.ajax({
        type: "POST",
        url: "http://myservlet.com/orders",
        data: { }
      }).done(function( msg ) {
         response = $.parseJSON(msg);
         $.each(response, function(key,value) {
              alert(value.order_id);
              var item = 0;
              $("#ordersTable tbody").append(
                      "<tr>"+
                         "<td><img src=http://examplewebsiteurl.com/plus.png id='item'></img></td>"+
                         "<td>"+value.order_id+"</td>"+
                         "<td>"+value.sku+"</td>"+
                         "<td>"+value.quantity_purchased+"</td>"+
                         "<td>"+value.product_name+"</td>"+
                         "<td>"+value.buyer_name+"</td>"+
                         "<td>"+value.buyer_phone_number+"</td>"+
                      "</tr>"
                       );
            });
      });

}
dimlee
  • 452
  • 1
  • 10
  • 22

2 Answers2

0

Try like

$(document).on('click', '#item', function() {
alert("test");
});
Arunkumar
  • 5,150
  • 4
  • 28
  • 40
0

Loading data is asynchronous operation that's why you can't bind anything before DOM is populated. You can provide a callback function to be called once data has come and available. Or you can use the fact that $.ajax is Promise object. For example:

function loadData() {
    return $.ajax({
        type: "POST",
        url: "http://myservlet.com/orders",
        data: {}
    }).done(function (msg) {
        $.each(response, function (key, value) {
            var item = 0;
            $("#ordersTable tbody").append(
                "<tr>" +
                "<td><img src=http://examplewebsiteurl.com/plus.png class='item'/></td>" +
                "<td>" + value.order_id + "</td>" +
                "<td>" + value.sku + "</td>" +
                "<td>" + value.quantity_purchased + "</td>" +
                "<td>" + value.product_name + "</td>" +
                "<td>" + value.buyer_name + "</td>" +
                "<td>" + value.buyer_phone_number + "</td>" +
                "</tr>");
        });
    });
}

loadData().done(function() {
    $(".item").bind("click", function() { alert("test"); });
});
dfsq
  • 191,768
  • 25
  • 236
  • 258