'Select only the clicked button JQuery

I have this ajax function, which should change the style of the clicked button, but for some reason it does not work. I'm not getting any errors in the console and the ajax call is successful Any idea what's wrong here?

function AcceptOffer(id)
{
    var json = {
        id : id
    };

    $.ajax({
        type: 'POST',
        url: "@Url.Action("AcceptOffer", "Product")",
        dataType : "json",
        data: {"json": JSON.stringify(json)},
        success: function() {
            $(this).text("Accepted");
            $(this).css("background-color", "green");
            $(this).css("color", "white");
            $(this).attr('disabled', true);

        },
        error: function(data) {
            alert('Some error');
            window.location.reload();
        }
    });
}
</script> 

Html:

<a href="javascript:void(0)" onclick="AcceptOffer('@item.OfferId')" class="btn btn-default acceptbtn">Accept</a>



Solution 1:[1]

Your issue is with using this incorrectly. The way you are using it, it is going to reference the object you pass into the ajax command

function AcceptOffer(id)
{
    var json = {
        id : id
    };

    var elemYouWantToChange =...;

    $.ajax({
        type: 'POST',
        url: "@Url.Action("AcceptOffer", "Product")",
        dataType : "json",
        data: {"json": JSON.stringify(json)},
        success: function() {
            $(elemYouWantToChange).text("Accepted");
            $(elemYouWantToChange).css("background-color", "green");
            $(elemYouWantToChange).css("color", "white");
            $(elemYouWantToChange).attr('disabled', true);

        },
        error: function(data) {
            alert('Some error');
            window.location.reload();
        }
    });
}

-- Edit --

In javascript, you listen for a click like so:

elem.addEventListener('click', function(e) {
  console.log(e.target); // You need to get e.target to AcceptOffer so it can style the correct element
  AcceptOffer(...);
});

Solution 2:[2]

In your code this is not pointing to the anchor tag you just need to pass this reference to your function.

function AcceptOffer(ele, id)
{
var json = {
    id : id
};

$.ajax({
    type: 'POST',
    url: "@Url.Action("AcceptOffer", "Product")",
    dataType : "json",
    data: {"json": JSON.stringify(json)},
    success: function() {
        $(ele).text("Accepted");
        $(ele).css("background-color", "green");
        $(ele).css("color", "white");
        $(ele).attr('disabled', true);

    },
    error: function(data) {
        alert('Some error');
        window.location.reload();
    }
});
}

So the anchor tag will be:

<a href="javascript:void(0)" onclick="AcceptOffer(this, '@item.OfferId')" class="btn btn-default acceptbtn">Accept</a>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mateen