This is actually what the problem was from the onset. Itâs the answer to the question âUnable to append ajax data on preexisting tagâ. I was unwittingly emptying both tags at the same time since they both had a common main
parent. And only had an epiphany later on.
Ok. So how do I filter only the section which is what I need? Keep in my mind that Iâm unable to manipulate any jquery object if they have no context. I donât remember the specific error it threw then but it was something in the region of âundefined contextâ and then a stack trace. In all the cases Iâve experienced that, appending it to the body (giving it a context i.e document) was a nifty workaround.
This morning, I tried reproducing the error for the purpose of this reply.
$.post(url, $('form').serialize(), function (data) {
var z = $('main > section').empty(), h = $('<div/>').html(data).find($('div section'));
console.log(h)
z.append(h);
It didnât throw any errors this time, but in the console, it logs [prevObject: init(1), context: undefined]
meaning the newly created DIV has no context and as such, cannot find or perform as a DOM element.
So I agree your argument about bandwidth and overheard are valid but I cannot presently come up with a better alternative.
Doesnât this mean reattaching the handler afresh? I mean, I think without explicitly calling removeEventListener
or off
, there is no clean way to escape reattaching the handler the few times the user will make those ajax calls during his stay on the page. Iâll post my handler for the callback here so you can demonstrate how you think I could create a bindEvents function.
function boot(e) {
e.preventDefault();
var l = $(this).attr('href') || $(this).attr('action'), f = l.match(/([a-z]+)/)[1], p = $('<link/>').attr({href: `${f}.css`, rel: 'stylesheet', type: 'text/css'}), w = e.target, t = 0, b = {
a: function() {
$('section').load(`${l} section`, function() {
if(l.indexOf('tran') > -1 && !t) {
$.getScript('r.js');
t = 1
}
else if (l.indexOf('rvt') > -1) $('a:contains("dashboard")').trigger('click');
// ideally, this should be wrapped in a condition confirming these elements are in the dom
$('.cus a').click(boot);
$('form').submit(boot);
});
},
form: function () {
$.post(l, $('form').serialize(), function (data) {
var z = $('main > section, main > section form').empty(), h = $('<div/>').html(data), x = $('body').append(h).find($('#transfer-complete, div section'));
z.append(x);
$('#transfer-complete a').click(boot);
$('#submit-modal').show(155);
setTimeout(function(){$('#submit-modal').hide('slow');}, 3000);
h.remove();
})
}
};
$('title').before(p);
for (var d in b) {
if (w.matches(d)) b[d]();
}
}
The markup you posted earlier is correct. Any further explanations you need, you can simply ask for.
Note: the current version works. The bone of contention is an event delegation model that precludes appending the whole document each time and still attaching the handler to the desired elements.