Search code examples
javascriptjqueryajaxcolorboxcustom-data-attribute

colorbox: send data-attr with post data


I'm opening a colorbox (AJAX page) for each link that has the data-myid attribute within my selector and I like to send the data-myid attribute value with the post request to get the right page back.

$(".gallery-media-cover a[data-myid]").colorbox({
    href: 'ajax/view//image',
    data: {
        myid: $(this).attr("data-myid"),
    },
});

It works when I just write: myid: 123 but they are dynamic, so I need to get them from the link. Whenever I try, the myid gets posted as undefined when I use $(this).attr("data-myid")

I really tried any possible way of getting the data attribute of the url to send it with my request, but none seems to work. I'm 100% sure data-myid is in the link.

Also

myid: function() {
    return $(this).attr("data-myid");
}

and

$(this).data("id")

stay undefined, I'm really without options here. Can anyone share a light on this?


Solution

  • In the context of the object you provide to the colourbox() method this does not refer to the link that was clicked on. To achieve what you require you could loop over each link and instantiate the colour box individually:

    $(".gallery-media-cover a[data-myid]").each(function() {
        var $el = $(this);
        $el.colorbox({
            href: 'ajax/view//image',
            data: {
                myid: $el.data('myid'),
            },
        });
    });