Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change inner text after ajax call back doesn't work?

I have ten like buttons on a page, that I create by a foreach loop on the page.

I have problem in changing the inner text with jQuery.

Let me explain with my elements

     <a class="pr-endorse" id="<%=product.ConfectionaryProductId %>">
        <i class="pr-add"></i>
        <span>+</span>
        <span class="pr-likes"><%=product.EndorsementCount %></span>
    </a>

This one of my like button elements.

And this is the Ajax function to submit the user like

      $(document).ready(function () {
        $(".pr-endorse").click(function () {
            debugger;
            var productId = $(this).attr("id");
            var confId = $("#ConfectioneryId").val();
            var countNumber = $(this).find(".pr-likes").html();
            $.ajax({
                url: '<%: Url.Action("Endorsement","Confectionery")%>',
                data: { productId: productId, itemId: confId },
                type: "POST",
                async: true,
                cache: false,
                success: function (result) {

                    debugger;
                    $(this).find(".pr-likes").text(result.endoresCount);
                    alert(result.endoresCount);

                },
                error: function (xhr) {
                    alert(xhr);
                }

I thing that this part of code should solve

  $(this).find(".pr-likes").text(result.endoresCount);

but it does not work ?

like image 645
salar Avatar asked Oct 31 '22 06:10

salar


1 Answers

I'll give it a try, it should probably look like this

$(document).ready(function () {
    $(".pr-endorse").click(function () {

        var self        = this
        var productId   = self.id;
        var confId      = $("#ConfectioneryId").val();
        var countNumber = $(this).find(".pr-likes").html();

        $.ajax({
            type : "POST",
            url  : '<%: Url.Action("Endorsement","Confectionery")%>',
            data : {
                productId : productId,
                itemId    : confId
            },
            dataType : 'json',
            success : function (result) {

                $(self).find(".pr-likes").text(result.endoresCount);
                alert(result.endoresCount);

            },
            error : function (xhr) {
                alert(xhr);
            }
        });
    });
});

Note that this inside the success function is not the element that was clicked, and to return an object you'd generally want to set the dataType, even if jQuery will parse it if the headers are correct.

like image 128
adeneo Avatar answered Nov 08 '22 08:11

adeneo