MattyMc MattyMc - 19 days ago 5
Ajax Question

Too Much Recursion When Dynamically Adding Click Event Listener With Post to a Div Element

I am getting 'too much recursion' errors with dynamically adding a click handler to div tags with a given class name ('reportLink' in this example) and cannot figure out what the issue is (scope issue?). The code works fine if I console.log the div's innerText, but fails when I add an ajax post to it. Does anyone see the issue here? Thank you for your help!

(function () {
const links = document.querySelectorAll(".reportLink");
const userName = document.getElementById("userName");

for (let i = 0; i < links.length; i++) {
let link = links[i];
createEvent(link);
}

function createEvent(element) {
var etext = element.innerText;

element.addEventListener("click", function () {
$.ajax({
url: 'route/myroute',
type: 'POST',
data: { user: userName, reportName: etext },
success: function (data) {
//console.log(data);
}
});
});
}


})();

Answer

Maybe try this syntax instead:

$("body").on("click", ".reportLink", function(e) {
    // Use $(this) for the element and get your other data..

    $.ajax({
        url: 'route/myroute',
        type: 'POST',
        data: { user: userName, reportName: etext },
        success: function (data) {
             //console.log(data);
        }
    });
});