DN0300 DN0300 - 5 months ago 16
Javascript Question

Open multiple dynamic links with the same ajax call

I am displaying multiple dynamic links which use the same , ajaxloads the content on the first link fine but doesn't work for the rest of them. How can I get it to load the content of other links in the same div?

Html:

$string .= '<a id="hrefid" data-id="'.$name["id"].'" href="link" >'.$name["name"].'</a>'.
<div id="content"> </div>


Jquery:

$('#hrefid').on('click', function (e) {
var load = $(e.target).attr("href");
if(load == "#link") {
$.ajax({
type: 'post',
url: "/page/test/"+id,
complete: function (event) {
$("#content").contents().remove();
$("#content").append(event.responseText);
}
});
}
});

Answer

Change the id to a class, remove # from the if statement

$string .= '<a class="hrefid" data-id="'.$name["id"].'" href="link" >'.$name["name"].'</a>'.
<div class="content"> </div>

$('.hrefid').on('click', function (e) {
    var el = $(this);
    var load = $(e.target).attr("href");
    if(load == "link") {
        $.ajax({
            type: 'post',
            url: "/page/test/"+id,
            success: function (event) {
                el.next().empty();
                el.next().append(event.responseText);
            }
        });
    }
    });