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");
});
}
});
});