0

I have a jQuery ajax code that works perfectly. But I need it to change the class of the button that fires the jQuery ajax event when clicked when successful. But my code on sucess: doesn't work. Please see code below.

jQuery Code

    $(document).ready(function() {
        $('.btn.btn-outline.btn-sm').click(function() {
            var pollQId = $(this).val();
            $.ajax({
                type: "POST",
                url: "Default.aspx/LikePoll",
                data: JSON.stringify({ 'pollQId': pollQId }),
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                success: function() {
                    $(this).addClass("btn btn-primary btn-sm");
                },

                error: function(response) {
                    alert(response.d);
                }
            });
        });
    })

Please help me. Many Thanks.

1 Answer 1

1

The this in the success callback is not the this you expect, to make this param consistent to the clicked button, pass context: this as additional param to your .ajax function.

You can find more info from jQuery.ajax:

context

  • Type: PlainObject
  • This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings
    used in the call ($.ajaxSettings merged with the settings passed to
    $.ajax).
$(document).ready(function() {
        $('.btn.btn-outline.btn-sm').click(function() {
            var pollQId = $(this).val();
            $.ajax({
                type: "POST",
                url: "Default.aspx/LikePoll",
                data: JSON.stringify({ 'pollQId': pollQId }),
                contentType: "application/json; charset=utf-8",
                datatype: "json",

                // Add this param, so the `this` in the success callback
                // will be the clicked button.
                context: this,

                success: function() {
                    $(this).addClass("btn btn-primary btn-sm");
                },

                error: function(response) {
                    alert(response.d);
                }
            });
        });
    })
Sign up to request clarification or add additional context in comments.

1 Comment

You are the greatest! Thanks so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.