Search code examples
javascriptjqueryajax

Why does Trying to make an ajax call attached to a class on load fail with multiple elements?


The attachment shows in console, but the ajax call is never made.

This is the HTML I am using to attach the ajax call:

<tr>
    <td>Sitename1</td>
    <td class="ajax-delsite" data-site="sitename1" id="sitename1">
    </td>
</tr>
<tr>
    <td>Sitename2</td>' . "\n";
    <td class="ajax-delsite" data-site="sitename2" id="sitename2">
    </td>
</tr>

And this is the jquery that is failing:

$(".ajax-delsite").on('load', function(e){
    var site = $(this).data("site");
    $.ajax({
        url: "/ajax/remove-site.php",
        type: "POST",
        data: { site: site },
        success: function(feedback){ 
            $("#ajaxResult").html(feedback);
        }
    });
});

What am I doing wrong?

UPDATE: Thanks in large part to DankDizaster's solution, I ended up fixing it with this:

$(".ajax-delsite").each(function(e){
    var site = $(this).data("site");
    $.ajax({
        url: "/ajax/remove-site.php",
        type: "POST",
        data: { site: site },
        success: function(feedback){ 
            $('#'+site).html(feedback);
        }
    });
});

Solution

  • load is not supported by the td element, you can read more about supported elements here.

    In your case you could use the JQuery's document ready

    $(document).ready(function () {
        const site = $(".ajax-delsite").data("site");
        $.ajax({
            url: "/ajax/remove-site.php",
            type: "POST",
            data: { site: site },
            success: function (feedback) {
                $("#ajaxResult").html(feedback);
            }
        });
    });