-1

Can somebody see what I'm missing? I've been stuck on this for a while now. I've got a ajax post which dynamically loads products.content.php into my page. I want to bind a click event to a button which is created through this post, but I can only get it working when the data isn't loaded by ajax.

            $.post('product.content.php',{'page': 0}, function(data) {

            $("#products").append(data); //append data received from server

        }).fail(function(xhr, ajaxOptions, thrownError) { 
            alert(thrownError); //alert any HTTP error
        });         

Works well, but then when I'd like to bind a click event to the appended data i recieve an error 'TypeError: thisSectionID is undefined' even after I delegated the event. (EDIT: changed var thisSectionID to $(this).attr('id'); to find clicked buttons ID instead of closest div ID)

        $(document).on('click', '.popup_open', function () {

            var thisSectionID   = $(this).closest('div').attr('id');
            var pidValSplitter   = thisSectionID.split("_");
            var pidVal         = pidValSplitter[1];

            var productPopup     = $("#product_popup");

            productPopup.popup("show");
            productPopup.html('<i class="fa fa-circle-o-notch fa-spin"></i>');

            productPopup.load("product.popup.php", {'pid':pidVal}, 
                function (responseText, textStatus, req) {
                    if (textStatus == "error") {

                      productPopup.empty();
                      productPopup.popup("hide");

                    }else{
                      productPopup.empty();
                      productPopup.html(responseText);

                          $('form').on('submit', function (e) {
                              var action                  = "voegtoe";

                              var aantalVal                = $("#aantal_" + pidVal).val();

                              var dataString = 'action='+ action + '&pid=' + pidVal + '&aantal=' + aantalVal;

                              var thisRow = $(this).closest('.row');
                              thisRow.empty();
                              thisRow.html('<i class="fa fa-circle-o-notch fa-spin"></i>');

                              $.ajax({
                                  type: 'post',
                                  url: 'functions.php',
                                  data: dataString,
                                  success: function (theResponse) {

                                      productPopup.empty();
                                      productPopup.popup("hide");
                                      $("#cart_popup").popup("show");
                                      $(".cart").html(theResponse);         

                                  },
                                  error: function (jXHR, textStatus, errorThrown) {
                                      alert(errorThrown);
                                  }
                              });
                              e.preventDefault();
                          });

                          $('.product-popup-close').click(function (e) {
                              e.preventDefault();
                              productPopup.empty();
                              productPopup.popup("hide");
                          });

                    }
            });

        });
Display name
  • 523
  • 1
  • 6
  • 12
  • You should use delegate events or append your event handler inside the ajax success function – kosmos Apr 20 '15 at 10:27
  • I've tried both ways but I keep getting an error that 'thisSectionID' is undefined' – Display name Apr 20 '15 at 10:35
  • Look if `var thisSectionID = $(this).closest('div').attr('id');` is properly assigned. – kosmos Apr 20 '15 at 10:39
  • I really don't now how to do it better than I already did :) I'm looking for the closest id of the div the .popup_open button is in, when I try this on not ajax loaded content it's working just fine. Once I loaded the content dynamically it seems it can't find the closest div around. – Display name Apr 20 '15 at 10:47
  • 1
    Debug your code and insert a breakpoint where you declare your `pidValSplitter` variable. Run the code and look if its above variable is undefined. If it is, `$(this).closest('div').attr('id');` is undefined. – kosmos Apr 20 '15 at 10:51
  • So it is undefined... But how to properly define it then? – Display name Apr 20 '15 at 10:55
  • I altered the code to look for the id of the clicked button instead of the closest div.id... Surprisingly it worked... Any ideas why it only works on $(this).attr('id'); and not on $(this).closest('div').attr('id'); – Display name Apr 20 '15 at 11:05
  • Since I can't see your html code, I can't help you with that. Anyway, take a look at [jQuery Docs .closest()](https://api.jquery.com/closest/) – kosmos Apr 20 '15 at 11:07
  • I found the problem in my code I guess... It was a nested div inside the div I was trying to get the code of; `
    `, so the closest div didn't have the actual ID i was looking for. Thanx for helping out!!
    – Display name Apr 20 '15 at 11:09
  • You can get the id using something like `$('.popup_open').parents('div').eq(1).attr('id')`. Remember to add an `/` before close the button tag. – kosmos Apr 20 '15 at 11:21

1 Answers1

3

To bind an event on a dynamically created element use on() function:

$(document).on('click', '#new_element', function() {
   // Your function here ...
});
kapantzak
  • 11,610
  • 4
  • 39
  • 61